jstl
Set scoped variables with JSTL in JSP Page
In this example we shall show you how to set scoped variables in a JSP Page, using JSTL. The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications. The JSTL tags can be classified, according to their functions, into Core tags, Formatting tags, SQL tags and XML tags and they can be used when creating a JSP page. To set variables with scope in a JSP Page, using JSTL one should perform the following steps:
- Create a jsp page that contains the
<%code fragment%>
scriptlet. It can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. - Include JSTL Core library in your JSP page, using the
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
syntax. - Use the
<c:set>
tag to set the result of an expression evaluation in a ‘scope’. It has three attributes,var
that is the name of the variable to store information,value
that is the information to save andscope
that is the scope of variable to store information. - Use the
<c:out>
tag to display the result of an expression. In itsvalue
attribute you can set the information to output. - Add JSP comment using the
<%-- --%>
tags.
as described in the code snippet below.
SetScopedVariablesJSTL.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %> <%@ taglib uri="/WEB-INF/tld/c-rt.tld" prefix="c-rt" %> <html> <head> <title>Java Code Geeks Snippets - Set Scoped Variables with JSTL in JSP Page</title> </head> <body> <%-- Set scoped variables --%> <c-rt:set var="var1" value="value1" scope="page" /> <c-rt:set var="var2" value="value2" scope="request" /> <c-rt:set var="var3" value="value3" scope="session" /> <c-rt:set var="var4" value="value4" scope="application" /> <%-- Print the values --%> var1: <c-rt:out value='${pageScope.var1}' /> <br/> var2: <c-rt:out value='${requestScope.var2}' /> <br/> var3: <c-rt:out value='${sessionScope.var3}' /> <br/> var4: <c-rt:out value='${applicationScope.var4}' /> <br/> <c-rt:set var="color" value="#dddddd" /> color: <c-rt:out value='${color}' /> <br/> </body>
URL:
http://localhost:8080/jcgsnippets/SetScopedVariablesJSTL.jsp
Output:
var1: value1
var2: value2
var3: value3
var4: value4
color: #dddddd
This was an example of how to set scoped variables in a JSP Page, using JSTL in Java.
I would like declare a variable in global state.It should be modified conditionally (when using c:if).How do we write it ? Thanks in Advance.