|[ Team LiB ]|
Recipe 16.5 Setting Session Attributes in Servlets
You want to store an object attribute in a session.
Use the javax.servlet.http.HttpSession class's setAttribute( ) method.
The mechanism for placing object attributes in sessions is very similar to storing objects in the ServletContext, which Recipe 16.1 described. The difference lies in the scope of the objects; in other words, which users and how many concurrent users can access the bound objects.
A session represents the interaction of a user with a web site. The sequence of web pages or components that a single user requests from a web site represents a single session (detailed in Chapter 11). Therefore, when you store an object instance in a session attribute, every user who participates in sessions interacts with his own instance of that object attribute. With ServletContext attributes, however, all of the application's users interact with the same attribute instance, since each web application has only one ServletContext and each context is associated with one attribute instance.
A shopping cart storing a user's item choices is an example of an object that web developers typically store as a session attribute. Example 16-7 shows a fragment of servlet code for storing an object in a session.
<!-- this code appears in the servlet's doGet or doPost method, whichever is appropriate - -> //Create a session if one does not exist yet HttpSession session = request.getSession( ); //bind an object attribute in the session if (session != null) session.setAttribute( "com.jspservletcookbook.ContextObject", new ContextObject( ));
Gain access to a session in a servlet by using the javax.servlet.http.HttpServletRequest object's getSession( ) method. Then call HttpSession.setAttribute( ), passing in the name of the attribute and an instance of the object attribute. The code in Example 16-7 uses the same ContextObject that Example 16-1 showed (Recipe 16.1). The ContextObject uses a synchronized java.util.Map type to handle multiple threads that might be using the attribute concurrently.
Recipe 16.1-Recipe 16.4 on handling ServletContext attributes in servlets and JSPs; Recipe 16.7 on accessing or removing session attributes in servlets; Recipe 16.6 and Recipe 16.8 on handling session attributes in JSPs; Recipe 16.9-Recipe 16.12 on handling request attributes in servlets and JSPs; Recipe 14.6 on using a session event listener; the Javadoc for javax.servlet.http.HttpSessionAttributeListener: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSessionAttributeListener.html.
|[ Team LiB ]|