1

If I set an attribute in my ServletContext object, does a view automatically have access to it? I'm trying to figure out how this JSP page is accessing a variable which is set in the ServletContextListener and nowhere else, so the only conclusion I can come up with is it must be available directly from the context object. If this is true, then what's the difference between setting a value in the ServletContext, and setting one in the request. Is it sort of like the difference between the session and the request?

slim
  • 2,545
  • 1
  • 24
  • 38
  • 1
    Food for read: http://stackoverflow.com/q/3106452 and http://stackoverflow.com/tags/el/info – BalusC Sep 24 '15 at 20:03

1 Answers1

3

Yes. You will have the access to it in JSP.

The Tomcat will convert/Generate servlets for all JSPs.

So you have almost same access what you have for Java Servlets in JSP too. That means both of them will have access to servletConfig.

All jsp generated servlets will extend HttpJspBase which intern extends GenericServlet and GenericServlet has the ServletConfig property. Check this doc.


ServletContext attributes are attributes at the container[tomcat] level, as per the docs

/**
 *
 * 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.
 *
 * <p>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 <code>/catalog</code>
 * and possibly installed via a <code>.war</code> file.)
 *

So there will be only one context per application and what ever the attributes you set will be accessible to all servlets, irrespective of any particular session or request.

Where as Session attributes are attributes set at the session level, there can be many sessions going on in the container and it is maintained by both the client[usually browser] and the container using session-id mechanism. You will have the access to the attributes set in a session, till the session ends.

Finally Request attributes lifetime is till you serve that request. Once your container sends back the result, the attributes you set will be destroyed.

Check the below javaDoc of ServletRequest.removeAttribute(...)

 /**
 * Removes an attribute from this request. This method is not generally
 * needed as attributes only persist as long as the request is being
 * handled.
 */
public void removeAttribute(String name);
rajuGT
  • 6,224
  • 2
  • 26
  • 44