JSTL Core Tags with Examples

In this article, we will discuss important JSTL core tags with examples.
JSTL core tags provide support for iteration, conditional logic, catch an exception, URL, forward or redirect response etc.
Let's list out all the JSTL core tags with description.

JSTL Core Tags List

1 <c:out> - Like <%= ... >, but for expressions.
2 <c:set > - Sets the result of an expression evaluation in a 'scope'
3 <c:remove > - Removes a scoped variable (from a particular scope, if specified).
4 <c:catch> - Catches any Throwable that occurs in its body and optionally exposes it.
5 <c:if> - Simple conditional tag which evalutes its body if the supplied condition is true.
6 <c:choose> - Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and .
7 <c:when> - Subtag of that includes its body if its condition evalutes to 'true'.
8 <c:otherwise > - Subtag of that follows the tags and runs only if all of the prior conditions evaluated to 'false'.
9 <c:import> - Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.
10 <c:forEach > - The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .
11 <c:forTokens> - Iterates over tokens, separated by the supplied delimiters.
12 <c:param> - Adds a parameter to a containing 'import' tag's URL.
13 <c:redirect > - Redirects to a new URL.
14 <c:url> - Creates a URL with optional query parameters

How to Use JSTL Core Tags?

To use JSTL core tags, we should include below a line of code in our JSP page:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Let's discuss important JSTL core tags with examples.

JSTL <c:forEach> Tag

<c:forEach> tag in JSTL is used for executing the same set of statements for a finite number of times. It’s similar to the for loop in java. This is a basic iteration tag, accepting many different collection types and supporting subsetting and other functionality.

Syntax of <c:forEach>

<c:forEach var="counter_variable_name" begin="intial_value" end="final_limit">
    //Block of statements
</c:forEach>
The below are the three main attributes of <c:forEach> tag.
  • begin: The initial counter value.
  • end: The final limit till which the loop will execute
  • var: Counter variable name

STL <c:forEach> Tag Example

In this example, we will iterator over a list of students using JSTL <c:forEach> tag.
Let's first create Student bean class:
package net.javaguides.jstl;

public class Student {

    private String firstName;
    private String lastName;
    private boolean goldCustomer;

    public Student(String firstName, String lastName, boolean goldCustomer) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.goldCustomer = goldCustomer;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public boolean isGoldCustomer() {
        return goldCustomer;
    }

    public void setGoldCustomer(boolean goldCustomer) {
        this.goldCustomer = goldCustomer;
    }
}
Let's create "for-each-student-test.jsp" JSP page and write code to iterator over a collection of students.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <%@ page import="java.util.*,net.javaguides.jstl.Student"%>

        <%
 // just create some sample data ... normally provided by MVC
 List<Student> data = new ArrayList<>();

 data.add(new Student("Ramesh", "Fadatare", false));
 data.add(new Student("John", "Cena", false));
 data.add(new Student("Tom", "Cruise", false));
 data.add(new Student("Tony", "Stark", false));
 data.add(new Student("Prakash", "Jadhav", true));
 pageContext.setAttribute("myStudents", data);
%>
            <html>

            <body>

                <h1>List of students</h1>
                <table border="1">

                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Gold Customer</th>
                    </tr>

                    <c:forEach var="tempStudent" items="${myStudents}">

                        <tr>
                            <td>${tempStudent.firstName}</td>
                            <td>${tempStudent.lastName}</td>
                            <td>${tempStudent.goldCustomer}</td>
                        </tr>

                    </c:forEach>

                </table>

            </body>

            </html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:

JSTL <c:choose>, <c:when>, <c:otherwise> Core Tags

These tags are used together like switch-case and default statements in Java. <c:choose> is the one which acts like switch, <c:when> like case which can be used multiple times inside <c:choose> for evaluating different-2 conditions. <c:otherwise> is similar to default statement which works when all the <c:when> statements holds false.

Syntax:

The basic structure looks like this –
<c:choose>
    <c:when test="${condition1}">
       //do something if condition1 is true
    </c:when>
    <c:when test="${condition2}">
        //do something if condition2 is true
    </c:when>
    <c:otherwise>
        //Statements which gets executed when all <c:when> tests are false.
    </c:otherwise>
</c:choose>

Example:

In this example, we will iterate over each student and check whether the student is a gold member or not: 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page import="java.util.*,net.javaguides.jstl.Student" %>

<%
 // just create some sample data ... normally provided by MVC
 List<Student> data = new ArrayList<>();

 data.add(new Student("Ramesh", "Fadatare", false));
 data.add(new Student("John", "Cena", false));
 data.add(new Student("Tom", "Cruise", false));
 data.add(new Student("Tony", "Stark", false));
 data.add(new Student("Prakash", "Jadhav", true));
 pageContext.setAttribute("myStudents", data);
%>

<html>

<body>
 <table border="1">

 <tr>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Gold Customer</th>
 </tr>
 
 <c:forEach var="tempStudent" items="${myStudents}">
  
  <tr>
   <td>${tempStudent.firstName}</td>
   <td>${tempStudent.lastName}</td>
   <td>
    <c:choose>
    
     <c:when test="${tempStudent.goldCustomer}">
      Special Discount
     </c:when>
     
     <c:otherwise>
      no soup for you!
     </c:otherwise>

    </c:choose>
    
   </td> 
  </tr>
  
 </c:forEach>

 </table>

</body>

</html>
Let's invoke this JSP page from a Web browser, you see the table on a browser:

JSTL <c:if> Core Tag

<c:if> is a JSTL core tag which is used for testing conditions. It is more or like an if statement in Java which evaluates a condition and executes a block of code if the result is true.

Syntax:

<c:if test="${condition}">
...
..
</c:if>

Example of <c:if> tag

In this example, we will test if the student is a gold member or not using <c:if> tag:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page import="java.util.*,net.javaguides.jstl.Student" %>

<%
 // just create some sample data ... normally provided by MVC
 List<Student> data = new ArrayList<>();

 data.add(new Student("Ramesh", "Fadatare", false));
 data.add(new Student("John", "Cena", false));
 data.add(new Student("Tom", "Cruise", false));
 data.add(new Student("Tony", "Stark", false));
 data.add(new Student("Prakash", "Jadhav", true));
 pageContext.setAttribute("myStudents", data);
%>

<html>

<body>
 <table border="1">

 <tr>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Gold Customer</th>
 </tr>
 
 <c:forEach var="tempStudent" items="${myStudents}">
  
  <tr>
   <td>${tempStudent.firstName}</td>
   <td>${tempStudent.lastName}</td>
   <td>
    <c:if test="${tempStudent.goldCustomer}">
     Special Discount
    </c:if>
    
    <c:if test="${not tempStudent.goldCustomer}">
     -
    </c:if>
    
   </td> 
  </tr>
  
 </c:forEach>

 </table>

</body>

</html>

Output

Notice that the output here, we have iterated over each student and we have checked the condition for a special discount of each student and printed the same against each student.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments