O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.7. Accessing or Removing Session Attributes in Servlets

Problem

You want to access or remove a session attribute in a servlet.

Solution

Use the javax.servlet.http.HttpSession.getAttribute( String attributeName ) method to access the attribute. Use the removeAttribute( String attributeName ) method to remove the attribute from the session.

Discussion

To access a session attribute, you must first bind the attribute to a session, as in Recipe 16.5. The object attribute is now available to the user associated with that session. Example 16-9 accesses an attribute named com.jspservletcookbook.ContextObject. The example just shows the code relating to accessing an attribute from the session. Example 16-5 in Recipe 16.3 shows the entire servlet and doGet( ) method for accessing an object attribute.

Tip

The HttpSession.getAttribute( ) method returns an Object type, so the return value has to be cast to the appropriate type before calling any methods on it.

Example 16-9. Gaining access to the session attribute in a servlet

package com.jspservletcookbook;
...
<!-- this code appears in the servlet's doGet or doPost method, whichever is appropriate. 
The ContextObject class is stored in WEB-INF/classes/com/jspservletcookbook/ -->

//Create a session if one does not exist yet
HttpSession session = request.getSession( );//This local variable will hold the object attribute ContextObject contextObj = null; //get access to an object attribute in the session if (session != null) contextObj = (ContextObject) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required