JSTL Core Tags:
JSTL – JavaServer Pages Standard Tag Library,
Component of the Java Web application which extends the JSP specification by adding a tag library of JSP tags.

JSTL helps us to avoid using java codes within JSP. JSTL tags can be classified into core, formatting, sql, xml and jstl function tags.

In this article we are going to see JSTL Core Tags. We are going to see some examples of JSTL core tags.

<c:set> – helps to set a value to variable
<c:out> – Used to print the value
<c:if> – If loop
<c:choose> – Similar to If else
<c:when> – used within <c:choose>
<c:forEach> – For loop
<c:forTokens> – For loop with Delimiter
<c:redirect> – Forwarding to another page
<c:url> – Forward to another url

For using JSTL core in JSP page, We need to import JSTL core library

<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>

The difference between forEach and forTokens is, forEach is similar to for loop in java. forTokens helps us to iterate over a collection by removing the delimiters (i.e .,/'”;:…etc). We will be able to understand once we go through the example code.

Now let us see an example for JSTL core tags,

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSTL</title>
    </head>
    <body>
         <c:set var="age" value="18"/> <!--Lets set a value for variable age -->
         The value set using c:Set is - <c:out value="${age}"/> <br><br> <!-- Printing the assigned value -->
         
         If loop in JSTL<br><br>
         <c:if test="${age >=18}"> <!-- If loop, checking the condition -->
             You are Eligible to Vote
         </c:if>
         <br><br>
         If Else <br><br>
         <c:set var="Age1" value="15"/>
         <c:choose> 
            <c:when test="${Age1 >=18}">
             You are Eligible to Vote
            </c:when>
            <c:otherwise>
                 You are Not Eligible to Vote
            </c:otherwise>
        </c:choose><br><br>    
        <c:forEach var="counter" begin="1" end="10">
            <c:out value="${counter}"/>
        </c:forEach>
                 
        <c:set var="List" value="Alpha,Beta,Charlie,Delta"></c:set>
        <br>
        <c:forTokens items="${List}" var="listitems" delims=",">
            <c:out value="${listitems}"/><br>
        </c:forTokens>
    </body>
</html>

Most of the functions are self-explanatory as they are similar to java functions.

op1

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *