In this post, you will learn how to use the <c:set> tag in the JSTL core tags library with code example.

This tag evaluates a given expression and sets the result into a variable. Optionally we can provide the scope in where the variable can be stored. Scope defaults to page.

 

JSTL <c:set> Syntax:

<c:set

   var="<string>"

   value="<string>"

   target="<string>"

   property="<string>"

   scope="<string>"/>



 

Attributes:

Name

Required

Type

Description

var

False

java.lang.String

Name of the variable to hold the result of the expression evaluated. The type of the variable is of type of the expression result evaluated.

value

False

java.lang.String

Expression to evaluate or information to save.

target

False

java.lang.String

In case of JavaBean or java.util.Map, this is the name of the object whose property to be set. If the target is a JavaBean, it must have a corresponding setter property

property

False

java.lang.String

In case of JavaBean or java.util.Map, this is the property of the object to set the value.

scope

False

java.lang.String

Scope of the variable. This specifies in which scope the variable will be placed. Default is page scope.

 

JSTL <c:set> Example:

The below example stores the username information in the session scope.

<c:set var="userName" scope="session" value="Code Java"/>
Value from session set by &lt;c:set&gt; tag: 
<c:out value="${userName}"/>

The below example sets the salary property to a value. In this case the employee object which resides in session scope must be a JavaBean and should have a setter setSalary(…). If employee object is a Map, then corresponding key (salary) will be set with the value given in the value attribute.

<c:set var=”employeeSalary” scope=”session” value=”$1000.00” target=”${employee}” property=”salary”/>
 

Output:

set-demo

 

Recommended Usage of JSTL <c:set> tag:

Particularly useful to set variables into a specified scope. Also useful to set JavaBean properties and setting values in a Map.

 

Other JSTL Core Tags:

if |  catch  |  choose   |  forEach  |  forTokens   |  import   |  out   |  param  |  redirect  |  remove   |  url


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment