<c:set> core JSTL tag is used for assigning a value to an object or variable within a specified scope. Let’s understand this with an example.
Here I’m assigning a string value to a variable name within application scope (it will let me access my variable in any of the JSP page across application). On the other page (display.jsp) I have printed the value on browser using <c:out> tag and EL.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Example of c:set tag</title> </head> <body> <c:set var="name" scope="application" value="Chaitanya Pratap Singh"/> <a href="display.jsp">Display</a> </body> </html>
display.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:out value="${name}"/>
Output:
Below are the screenshots of the above example’s output.
Attributes of <c:set> tag
1) value: It can be a hardcoded value or an expression. for e.g. below are the allowed variations of <c:set> tag –
The value of the variable myvar would be stored in the object name.
<c:set var="name" scope="application" value="${myvar}"/>
The result of the expression would be stored in the object.
<c:set var="sum" scope="application" value="${1+3+6}"/>
2) var: It holds the variable/object name
3) scope: It can be request, session, page and application. In the above example we have specified the scope as application, however it can be anything out of the mentioned four. It all depends on the requirements.
Binh Thanh Nguyen says
Thanks, nice example.