[ Team LiB ] Previous Section Next Section

Recipe 16.12 Accessing or Removing Request Attributes in JSPs


You want to use a JSP to access or remove a request attribute.


Use the JSTL core tags c:out and c:remove to access and optionally remove the attribute.


Example 16-14 accesses an object attribute that is bound to the HttpServletRequest. The JSP accesses this attribute by using EL syntax inside the c:out JSTL tag.

Example 16-12 in Recipe 16.10 forwards a request attribute to a servlet using the jsp:forward standard action. The JSP in that example can forward its request attribute to the JSP in Example 16-14 by using the code:

<jsp:forward page="/requestDisplay.jsp" />

The code:


uses the requestScope JSTL implicit object. This variable, which the JSTL automatically makes available to EL-related code, is a java.util.Map type containing any attributes bound to the request scope. The code then displays the values the attribute contains by accessing the object attribute's values property (see Recipe 16.1 for a discussion of the object used for storing an attribute in various scopes throughout this chapter).

Example 16-14. Accessing and removing a request attribute with the JSTL
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<head><title>Request reading JSP</title></head>
<h2>Here are the values from the bound RequestObject</h2>

<c:out value=
        values}" escapeXml="false" />

<%-- c:remove may not be necessary as request attributes persist only as long as the 
request is being handled --%>
<br>Removing request attribute with c:remove ... <c:remove var=
    "com.jspservletcookbook.ContextObject" scope="request" />


The c:remove tag removes the attribute named in its var attribute from the specified scope. Use scope="request" because you are removing this attribute from the JSP's request scope. Figure 16-2 shows the output of the displayRequest.jsp page in a web browser.

Figure 16-2. The browser display after accessing and removing a request attribute in a JSP

The JSP that appears in the browser's address field, requestBind.jsp, actually set the attribute and forwarded the request (see Recipe 16.10). When code uses jsp:forward, the original JSP remains in the browser's address field, even though the browser displays the output of the JSP targeted by the forward action.

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-Recipe 16.8 on handling session attributes in servlets and JSPs; Recipe 16.11 on accessing or removing request attributes in servlets; the Javadoc for javax.servlet. ServletRequestAttributeListener: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletRequestAttributeListener.html.

    [ Team LiB ] Previous Section Next Section