joz
joz

Reputation: 722

Tomcat use of static variables

Is it possible to use static variables in my project to store data for all Servlets (they are in one .war file) and different requests? (It's not data that belongs to a distinct session)

Upvotes: 2

Views: 2115

Answers (4)

Suresh Atta
Suresh Atta

Reputation: 121998

data for all Servlets

You can use ServletContext for this.

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

For example: in web.xml

 <context-param>
    <param-name>param</param-name>
    <param-value>Myname is web xml</param-value>
  </context-param>

In your servlet

    public class ParameterServlet extends HttpServlet {

---

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext context = getServletContext();
    name= context.getInitParameter("param");
  }

A complete example here.

For Objects

setting

getServletContext().setAttribute("myObj", obj);

getting

MyObj attribute = (MyObj)getServletContext().getAttribute("myObj");

you can access those objects across servlets.

Upvotes: 2

anuu_online
anuu_online

Reputation: 384

Yes you can, the static variable will be accessible for all the servlet threads. But about using the static variable, you should make a proper decision depending on the factors like the life time of the data you want to store and the amount of data you are going to store.

And since it is used in servlets context, make sure that its thread-safe.

Upvotes: 0

smajlo
smajlo

Reputation: 972

in web.xml you can define

<context-param>
    <description>My variable</description>
    <param-name>variable.name</param-name>
    <param-value>value</param-value>
</context-param>

And then access it from Servlet code:

String variable = getServletContext().getInitParameter("variable.name");

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Yes you can do that.

However it is better to define these constants in your web.xml using the <context-param> tag.

Servlets can then retrieve constants defined using the <context-param> tag using the call:

 context.getInitParameter()

Example of name-value pairs in web.xml:

  <context-param>
    <param-name>name</param-name>
    <param-value>Joe</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>password</param-value>
  </context-param>

Upvotes: 0

Related Questions