Recipe 16.10 Setting Request Attributes in JSPs


You want to set a request attribute using a JSP.


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


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 .

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="" 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}"/> <jsp:forward page="/displayAttr" />  

After setting the request attribute and giving it some values, the JSP forwards the request to the servlet path /displayAttr . The servlet or JSP mapped to that path has access to the new request attribute.

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 and Recipe 16.12 on accessing or removing request attributes in servlets and JSPs; the Javadoc for javax.servlet . ServletRequestAttributeListener :

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: