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.10. Setting Request Attributes in JSPs

Problem

You want to set a request attribute using a JSP.

Solution

Use the JSTL core tags and the jsp:useBean standard action to create an instance of an object and bind it to the request.

Discussion

The JSP in Example 16-12 stores a com.jspservletcookbook.ContextObject in the request scope by first creating an instance of that object with jsp:useBean. As in Recipe 16.2 and Recipe 16.6, the code uses the c:set tag to bind the object to the request, but this time gives its scope attribute a value of request.

Tip

You should store the classes for the objects that JSPs use as request attributes in WEB-INF/classes, or in WEB-INF/lib if the class is part of a JAR file.

The JSP in Example 16-12 is exactly like the JSP code shown in Recipe 16.2 and Recipe 16.6, except this time the code uses the requestScope implicit object to fetch the request attribute and give it a new property and value. The requestScope is used in EL syntax (see Chapter 23) to access request attributes.

Example 16-12. Setting a request attribute and forwarding the request in a JSP

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<jsp:useBean id="contextObj" class=
    "com.jspservletcookbook.ContextObject" />

<jsp:useBean id="date" class="java.util.Date" /> 
<c:set var="com.jspservletcookbook.ContextObject" value= "${contextObj}" scope="request" /> <c:set target= "${requestScope[\"com.jspservletcookbook.ContextObject\"].map}" value= "${date}" property="${pageContext.request.remoteAddr}"/> ...

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