Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet context scope vs global variable

Tags:

What (if any) is the difference between storing a variable in the ServletContext and just having it as a public static member of one of the classes?

Instead of writing:

// simplified (!) int counter = (Integer)getServletContext().getAttribute("counter"); counter++; this.getServletContext().setAttribute("counter", counter); 

Why not just have:

// in class MyServlet public static int counter = 0;  // in a method somewhere MyServlet.counter++; 

(Ignore concurrency issues, please, this is just a dumb example)

From what I can tell, these two options behave the same way under Tomcat. Is there something better about using the first option?

like image 887
itsadok Avatar asked Jul 26 '09 13:07

itsadok


People also ask

Is servlet instance globally scoped?

Yes! Different threads might be used to render request for different users but the same servlet instance is used.So yes the variable will be common to all requests.

What is the scope of ServletContext?

ServletContext. Context/Application scope begins when a webapp is started and ends when it is shutdown or reloaded. Parameters/attributes within the application scope will be available to all requests and sessions. The Context/Application object is available in a JSP page as an implicit object called application.


2 Answers

The web container knows about your servlet context, but not about your static variables which as skaffman says are private to your classloader.

Anything that cause two different requests to be served by an application instance in a different classloader (this could be server restarting, web application redeployment, or multi-node servers) will case your logic to break. The servlet context will survive these things as the web container knows about it and can serialize it or have a common repository.

like image 97
Thorbjørn Ravn Andersen Avatar answered Nov 15 '22 10:11

Thorbjørn Ravn Andersen


Well they're not quite the same; servlet-context-scope is private to the webapp, whereas static scope is private to the classloader. Depending on your container and how it's configured, these may or may not be the same. When thinking in terms of webapps and JavaEE, using a context-coped field is going to be more reliably portable. Also, context-scoped attributes are easier to access from JSPs, i.e. you don't need scriptlets to get to them.

like image 43
skaffman Avatar answered Nov 15 '22 11:11

skaffman