Open In App

JSTL Core <c:set> Tag

The <c:set> tag is used for variable creation and assignment in JSP pages. In this article, we will delve into the JSTL Core <c:set> tag, provide code samples, and illustrate the expected outputs. It is used to set the result of an expression evaluated in a “scope”.

Prerequisite of the topic

Syntax

<c:set  var="string"  value="string" target="string" property="string>  scope="string"/>

Attributes of <c:set>

Name

Description

Type

Required

var

Name of the variable to store the value

String

False

value

Expression to be evaluated

String

False

target

Target Object whose object is set. Must evaluate to a JavaBean with setter or java.util.Map Object

String

False

property

Name of the property to be set in the target object.

String

False

scope

Scope of the variable. Default is page scope

String

False

Declaring a variable

To declare any variables use the c:set tag to define the variable, and use the var attribute to name the object to be referenced later. Use the value attribute to set the actual value to the object. Once the variable is declared use expression syntax to access the object in that page. We can also use the <c:out> tag to display the expression.



Example of JSTL Core <c:set> Tag

Below is the implementation of the above topic:




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <c:set var="userName" value="ragul21" />
    <h1> Your user name is : ${userName} </h1>
</body>
</html>

Output:



Variable scopes

We can control the scope of a variable created with <c:set> by using the scope attribute. The possible values for the scope attribute are

Edxample of JSTL Core Variable Scopes




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <c:set var="count" value="42" scope="session" />
    <p>Count in session: ${count}</p>
</body>
</html>

Output:

Conclusion

The JSTL Core <c:set> tag is a versatile tool for variable creation and assignment in JSP pages. It helps improve code readability and maintainability by eliminating the need for scriptlet code. Whether you need to set values, control variable scope, or perform conditional assignments, the <c:set> tag empowers you to handle variables more efficiently in your JSP applications. By incorporating this tag into your JSP development, you can create cleaner, more robust, and more maintainable web applications.


Article Tags :