[ Team LiB ] |
![]() ![]() |
Recipe 23.9 Accessing Scoped Variables with the ELProblemYou want to grab and display the value of an object attribute using a JSTL custom tag. SolutionUse the EL and the c:out tag to get the value of an attribute that has been stored in a certain scope. DiscussionAn object such as a java.util.Date, a java.lang.Integer, or an object that you design, can be stored in four different scopes:
Example 23-10 uses the c:set JSTL tag to set a variable named com.jspservletcookbook.SessionObject to session scope. Then c:out accesses and displays the value of the variable. Example 23-10. Accessing the value of an object stored in session scope<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head><title>Accessing a Scoped Value</title></head>
<body>
<h2>Here is the value of the Session-Scoped Attribute</h2>
<c:set var=
"com.jspservletcookbook.SessionObject" value=
"My object attribute.<br />" scope="session" />
<c:out value=
"${sessionScope[\"com.jspservletcookbook.SessionObject\"]}" escapeXml="false" />
</body>
</html>
By convention, object attributes are named after fully qualified Java classes (usually, after the Java type of the stored object). Therefore, the attribute name has period characters (.) in it. This is the purpose of the syntax ${sessionScope[\"com.jspservletcookbook.SessionObject\"]}. If the attribute name does not contain periods, then you can use an EL expression consisting of just the variable name, without the sessionScope JSTL implicit object, in order to access the object attribute: <c:out value= "${SessionObject}" escapeXml="false" />
You must use the required characters of an EL expression (the dollar sign and curly braces surrounding the expression: "${ ... }"). Otherwise the c:out tag will just output a String literal such as "SessionObject." See AlsoThe Jakarta Project's Taglibs site: http://jakarta.apache.org/taglibs/index.html; Sun Microsystem's JSTL information page: http://java.sun.com/products/jsp/jstl/; Recipe 23.3 on using the core tags; Recipe 23.4 and Recipe 23.5 on using the XML tags; Recipe 23.6 on using the formatting tags; Recipe 23.7 and Recipe 23.8 on using the SQL JSTL tags; Recipe 23.10-Recipe 23.14 on using the EL to access request parameters, cookies, and JavaBean properties. ![]() |
[ Team LiB ] |
![]() ![]() |