Differences between Attributes in a Request, Session, and ServletContext

I am having trouble understanding the differences between these three ways of setting attributes:

// String as attribute of request req.setAttribute("name", "Sluggo"); // Integer as attribute of session req.getSession().setAttribute("age", 10); // Date as attribute of context getServletContext().setAttribute("today", new Date()); 
  • What are the differences?
  • When should you use each?
+9
source share
2 answers

These three have different applications:

  • request attributes live throughout the entire request / response cycle

  • session attributes for the life of this session

  • ServletContext is in the servlet context and lives until the context is destroyed.

+6
source

The ServletContext attribute is an object associated with the context through the ServletContext.setAttribute() method and available to ALL servlets (thus JSP) in this context or to other contexts through the getContext() method. By definition, a context attribute exists locally in the VM where they were defined. Therefore, they are not available in distributed applications.

Session attributes are bound to the session as a means of providing state for a set of related HTTP requests. Session attributes are available ONLY for those servlets that join the session. They are also not available for different JVMs in distributed scripts. Objects can be notified when they are / are not associated with a Session that implements the HttpSessionBindingListener interface.

Request attributes are tied to a specific request object, and they are valid until the request is resolved or until it is sent from the servlet to the servlet. They are more often used as a communication channel between RequestDispatcher through the RequestDispatcher interface (since you cannot add parameters ...) and the container. Query attributes are very useful in web applications when you need to provide tuning information between information providers and the information presentation layer (JSP) that is associated with a particular request and should no longer be available, which usually happens with sessions without strict control. strategy.

In conclusion, we can say that:

  • Context attributes are for infrastructure, such as shared connection pools.
  • Session attributes are for contextual information such as user identification.
  • Query attributes are for specific query information, such as query results.

Source: Servlets Interview Questions by Krishna Shrinivasan @ javabeat.net

+19
source

All Articles