Show TOC Start of Content Area

Procedure documentation Accessing and Manipulating the Session Object  Locate the document in its SAP Library structure

Use

This procedure refers to retrieving the session object that is associated with the current request (or creating one if no such object exists) and reading attributes that are set in the session object.

Procedure

You can access an HttpSession object in the service method of your servlet. Proceed as follows:

...

       1.      Use the request.getSession()method of the HttpServletRequest object. If a session object is already associated with the client request, this method returns it. If no such object exists on the server, it creates one for that client.

If you do not want to create a new session if one does not exist on the server for that client, you can use the request.getSession(false) method.

Some applications may need to know if the session is currently established and forward the client to a welcome or a login page (so that the client is aware that a new session is established on the server). You can run this check in your servlet using the HttpSession.isNew() method. If it returns true, the session is new and the client does not yet know about it.

Note

There is an alternative way to distinguish whether a new session is created for the current request. This is the case when you use the request.getSession(false) method and it returns null.

Note

If there is no session established, you must create it before you commit the response. The reason for this is that if you use cookies, you may have to override the header fields of the response object. The Java Servlet 2.5 Specification does not allow the servlet to modify the response headers after you have committed even part of the response.

Note

You can set a limit on the sessions that can exist simultaneously for your application. To do this, use <max-sessions> tags of the additional Web deployment descriptor of the Web application. If a servlet tries to create a session when the maximum number of sessions has been reached, a runtime exception will be thrown.

       2.      Use the getAttribute(String name) or getAttributesNames() methods of the HttpSession object to retrieve attributes that are associated with it. If you want to set a new attribute, or remove an existing one, use setAttribute() and removeAttribute(), respectively. Information that is stored into the session object appears as name-value pairs.

Example

public void doGet(HttpServletRequest request, HttpServletResponse response)

                  throws ServletException, IOException {

    // Get the user’s session and shopping cart

   HttpSession session = request.getSession();

   ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");

.....

   // Determine the total amount of the purchase

   double total = cart.getTotal();

 

 

End of Content Area