Programmingempire
In this article, I will explain When and How to Use JSTL Tags. Basically, we can use JSTL tags in place of the scriptlet.
When to Use JSTL Tags?
In general, we use the JSP Tag library in the following situations.
- For the purpose of reducing the number of lines of code, the corresponding JSTL tag is a good choice. In fact, the use of tags makes the code compact and more maintainable.
- Further, mixing the tags and scriptlet code is a bad practice. Therefore, by using tags, you can avoid much of the scriptlet code on a JSP page.
- Also, the use of tags simplifies the development.
The following section discusses some of the JSTL core tags.
Example of <c:out> tag
Whenever we need to display the result of an expression as the output on a web page, we can use the out tag with ācā as the prefix. The following code shows an example of the <c:out> tag. As can be seen in the code, in order to use variables created in a scriptlet, the use of the setAttribute() method is necessary.
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL out Tag</title>
</head>
<body>
<c:out value="This Output is Produced used the out Tag!!"/>
<br/>
<%
String s1="A Sample Text.";
pageContext.setAttribute("s1", s1);
int v1=89;
int v2=795;
pageContext.setAttribute("v1", v1);
pageContext.setAttribute("v2", v2);
%>
<c:out value="Accesing a variable from Scriptlet: ${s1}"/>
<br/>
<c:out value="Example of Expression: ${v1+v2}"/>
</body>
</html>
Output
Example of c:set Tag
Basically, the c:set tag evaluates the value of an expression and assigns this value to a variable. The following code shows how to find the sum of two numbers by creating three variables.
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL set Tag</title>
</head>
<body>
<c:set var="x" value="567"/>
<c:set var="y" value="45"/>
<c:set var="z" value="${x+y}"/>
<c:out value="Value of Expression = ${z}"/>
</body>
</html>
Output