Java Reference
In-Depth Information
Listing 3-37. Using Scope
<c:set var="helloVar" value="hello" scope="session" />
We could also have expressed this by providing the value in the body content of the action,
as illustrated in Listing 3-38.
Listing 3-38. Using <c:set>with Body
<c:set var="hello" scope="session" >
helloworld
</c:set>
The value of a variable can also be an EL expression, as illustrated in Listing 3-39.
Listing 3-39. Using an EL Expression in a Value
<c:set var="titleVar" value="${book.title}" scope="session" />
In Listing 3-39, the
title
property of the
book
bean is set in the
titleVar
variable.
Listing 3-40 shows the scriptlet equivalent of
<c:set>
, as illustrated in Listing 3-36.
Listing 3-40. Scriptlet Equivalent of <c:set>
<%
String helloVar = "hello";
pageContext.setAttribute("helloVar ", helloVar);
%>
Setting the Property of a Speciied Target Object
To be able to set bean properties or map values using
<c:set>
, we need to use
target
and
property
,
instead of
var
, which will define the bean and property name to be set. If
target
is
map
, for instance,
then
property
is the name of the key and
value
is the value for that key.
Here's the syntax:
<c:set value=""value""target=""target"" property=""propertyName""/>
If using a target object, the target must evaluate to a JavaBean or a
java.util.Map
object.
If the target is a JavaBean, it must contain the appropriate getter/setter
methods.
Listing 3-41 illustrates how to set a map key using a
<c:set>
tag.
Listing 3-41. Setting a Map Key using the <c:set>Tag
<c:set target="bookMap" property="id" value="1">
This is equivalent to
bookMap.put("id", "1");
. You can also supply the value in the body of the
<c:set>
tag.