[ Team LiB ] Previous Section Next Section

Recipe 16.8 Accessing or Removing Session Attributes in JSPs


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


Use the c:out JSTL core tag to display the value of an attribute and the c:remove tag to remove the attribute from the session.


Here are the steps to access or remove a session-scoped variable with the JSTL and a JSP:

  1. Make sure that your web application is able to use the JSTL (i.e., you have the proper JAR files such as jstl.jar and standard.jar in your WEB-INF/lib directory; see Chapter 23 for instructions).

  2. Include the taglib directive, which makes the JSTL core tags available to the JSP (see the upcoming code).

  3. Make sure the object attribute is bound to the session in the first place, either by the same JSP that accesses the attribute, or by another web component (such as a servlet).

The code in this recipe shows how to reference a session-scoped variable, as opposed to a ServletContext attribute (shown in Recipe 16.4). This code uses the sessionScope implicit object of the EL, which is an automatically available variable in EL format that contains any session-scoped object attributes. This code represents a portion of a JSP that displays the values contained in an attribute named com.jspservletcookbook.ContextObject.

Example 16-4 in Recipe 16.2 shows a complete JSP that accesses object attributes. Recipe 16.2 accesses a ServletContext attribute in a JSP, rather than a session-scoped attribute.

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
//HTML or other presentation code here...
<c:out value=
        escapeXml="false" />

The escapeXml="false" part of the c:out tag tells the tag to leave characters that are part of the tag's output such as < and > unescaped (in other words, do not convert them to character entities such as &lt; and &gt;).

This JSP code removes a session-scoped variable using the c:remove core tag:

<c:remove var=
    "com.jspservletcookbook.ContextObject" scope="session" />

The object attribute is no longer available for the individual session associated with the user that requested this JSP. In other words, the c:remove tag does not remove all session attributes of the specified name, just the session attribute(s) associated with any user who requests the JSP containing the c:remove tag.

See Also

Chapter 23 on using the JSTL; Recipe 16.1-Recipe 16.4 on handling ServletContext attributes in servlets and JSPs; Recipe 16.5 on setting session attributes in servlets; Recipe 16.6 on setting session attributes in JSPs; Recipe 16.7 on accessing or removing session attributes in servlets; 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 ] Previous Section Next Section