March 2, 2011

JSTL 1.1 - <c:set> example

Example 1: Setting an attribute in some scope

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="userType" scope="request" value="premium" />
<c:out value="${requestScope.userType}" default="normal" />

prints,

premium


Example 2: setting JavaBean property
Note: PersonBean.java is a simple JavaBean with properties firstName and age


<%@ page import="info.icontraining.beans.PersonBean"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
 PersonBean p = new PersonBean();
 session.setAttribute("person", p);
%>
<c:set target="${sessionScope.person}" property="firstName" value="Dinesh" />
<c:set target="${sessionScope.person}" property="age" value="32" />
<c:out value="${sessionScope.person.firstName}" /><br/>
<c:out value="${sessionScope.person.age}" /><br/>


prints,

Dinesh
32


Example 2: setting a key-value pair in a Map
Note: PersonBean.java is a simple JavaBean with properties firstName and age

<%@ page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% 
   Map m = new HashMap();
   session.setAttribute("map", m);
%>
<c:set target="${sessionScope.map}" property="firstName" value="Dinesh" />
<c:set target="${sessionScope.map}" property="lastName" value="PC" />
<c:out value="${sessionScope.map.firstName}" /><br/>
<c:out value="${sessionScope.map.lastName}" /><br/>

prints,

Dinesh
PC

1 comment: