c:set

The JSTL tag c:set is way more powerful than the jsp:setProperty standard action that is meant just for setting the property for a JavaBean.

With c:set we can also set a value, and create a new key-value pair, in a map and even setting a new attribute in a specified scope (or changing its value if it already exists - or even destroying it, if we pass null as value).

To create an attribute, we specify its name, its value, and where we want to put it. By default the c:set puts a new attribute in the page scope, so after this code:
<c:set var="user" scope="session" value="Tom" />
<c:set var="dog" value="${fido}" />
We have a "user" attribute in the session scope ("Tom"), and a "dog" in the page scope - assuming that "fido" is an object already created.

If "fido" was a JavaBean with a "name" property, we could change its value:
<c:set target="${fido}" property="name" value="Clover" />
If we have "states", a Map<String, String> where the keys are nation names and values are their capitol city, if there is among them "Sweden", we can change its associated value in this way:
<c:set target="${states}" property="Sweden" value="Stockholm" />
Or we can add a new pair:
<c:set target="${states}" property="Spain" value="Madrid" />
More details on Head First Servlet and JSP, chapter nine. I was reading this cool book while I wrote this post.

No comments:

Post a Comment