Tutorial

JSTL Tutorial, JSTL Tags Example

Published on August 3, 2022
author

Pankaj

JSTL Tutorial, JSTL Tags Example

JSTL stands for JSP Standard Tag Library. JSTL is the standard tag library that provides tags to control the JSP page behavior. JSTL tags can be used for iteration and control statements, internationalization, SQL etc. We will look into JSTL Tags in detail in this JSTL tutorial. Earlier we saw how we can use JSP EL and JSP Action Tags to write JSP code like HTML but their functionality is very limited. For example, we can’t loop through a collection using EL or action elements and we can’t escape HTML tags to show them like text in client side. This is where JSTL tags comes handy because we can do much more from JSTL tags.

JSTL

JSTL, JSTL Tutorial, JSTL Tags, JSTL Example, JSTL Core Tags JSTL is part of the Java EE API and included in most servlet containers. But to use JSTL in our JSP pages, we need to download the JSTL jars for your servlet container. Most of the times, you can find them in the example projects of server download and you can use them. You need to include these libraries in your web application project WEB-INF/lib directory.

JSTL jars

JSTL jars are container specific, for example in Tomcat, we need to include jstl.jar and standard.jar jar files in project build path. If they are not present in the container lib directory, you should include them into your application. If you have maven project, below dependencies should be added in pom.xml file or else you will get following error in JSP pages - eclipse Can not find the tag library descriptor for "https://java.sun.com/jsp/jstl/ core"

<dependency>
	<groupId>jstl</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>

JSTL Tags

Based on the JSTL functions, they are categorized into five types.

  1. JSTL Core Tags: JSTL Core tags provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc. To use JSTL core tags, we should include it in the JSP page like below.

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

    In this article, we will look into important JSTL core tags.

  2. JSTL Formatting and Localisation Tags: JSTL Formatting tags are provided for formatting of Numbers, Dates and i18n support through locales and resource bundles. We can include these jstl tags in JSP with below syntax:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    
  3. JSTL SQL Tags: JSTL SQL Tags provide support for interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags we can run database queries, we include these JSTL tags in JSP with below syntax:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    
  4. JSTL XML Tags: JSTL XML tags are used to work with XML documents such as parsing XML, transforming XML data and XPath expressions evaluation. Syntax to include JSTL XML tags in JSP page is:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/xml" prefix="x" %>
    
  5. JSTL Functions Tags: JSTL tags provide a number of functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc. Syntax to include JSTL functions in JSP page is:

    <%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    

Note that all the JSTL standard tags URI starts with https://java.sun.com/jsp/jstl/ and we can use any prefix we want but it’s best practice to use the prefix defined above because everybody uses them, so it will not create any confusion.

JSTL Core Tags

JSTL Core Tags are listed in the below table.

JSTL Core Tag Description
<c:out> To write something in JSP page, we can use EL also with this tag
<c:import> Same as jsp:include or include directive
<c:redirect> redirect request to another resource
<c:set> To set the variable value in given scope.
<c:remove> To remove the variable from given scope
<c:catch> To catch the exception and wrap it into an object.
<c:if> Simple conditional logic, used with EL and we can use it to process the exception from <c:catch>
<c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <c:when> and <c:otherwise>
<c:when> Subtag of <c:choose> that includes its body if its condition evalutes to ‘true’.
<c:otherwise> Subtag of <c:choose> that includes its body if its condition evalutes to ‘false’.
<c:forEach> for iteration over a collection
<c:forTokens> for iteration over tokens separated by a delimiter.
<c:param> used with <c:import> to pass parameters
<c:url> to create a URL with optional query string parameters

JSTL Tutorial

Let’s see some of the JSTL core tags usages in a simple web application. Our project will include a Java Bean and we will create a list of objects and set some attributes that will be used in the JSP. JSP page will show how to iterate over a collection, using conditional logic with EL and some other common usage. JSTL Tags Example, JSTL Tutorial, JSTL Example, JSTL

JSTL Tutorial - Java Bean Class

package com.journaldev.model;

public class Employee {

	private int id;
	private String name;
	private String role;
	public Employee() {
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}

}

JSTL Tutorial - Servlet Class

package com.journaldev.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.journaldev.model.Employee;

@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Employee> empList = new ArrayList<Employee>();
		Employee emp1 = new Employee();
		emp1.setId(1); emp1.setName("Pankaj");emp1.setRole("Developer");
		Employee emp2 = new Employee();
		emp2.setId(2); emp2.setName("Meghna");emp2.setRole("Manager");
		empList.add(emp1);empList.add(emp2);
		request.setAttribute("empList", empList);
		
		request.setAttribute("htmlTagData", "<br/> creates a new line.");
		request.setAttribute("url", "https://www.journaldev.com");
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");
		rd.forward(request, response);
	}

}

JSTL Tutorial - JSP Page

home.jsp code:

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<style>
table,th,td
{
border:1px solid black;
}
</style>
</head>
<body>
<%-- Using JSTL forEach and out to loop a list and display items in table --%>
<table>
<tbody>
<tr><th>ID</th><th>Name</th><th>Role</th></tr>
<c:forEach items="${requestScope.empList}" var="emp">
<tr><td><c:out value="${emp.id}"></c:out></td>
<td><c:out value="${emp.name}"></c:out></td>
<td><c:out value="${emp.role}"></c:out></td></tr>
</c:forEach>
</tbody>
</table>
<br><br>
<%-- simple c:if and c:out example with HTML escaping --%>
<c:if test="${requestScope.htmlTagData ne null }">
<c:out value="${requestScope.htmlTagData}" escapeXml="true"></c:out>
</c:if>
<br><br>
<%-- c:set example to set variable value --%>
<c:set var="id" value="5" scope="request"></c:set>
<c:out value="${requestScope.id }" ></c:out>
<br><br>
<%-- c:catch example --%>
<c:catch var ="exception">
   <% int x = 5/0;%>
</c:catch>

<c:if test = "${exception ne null}">
   <p>Exception is : ${exception} <br>
   Exception Message: ${exception.message}</p>
</c:if>
<br><br>
<%-- c:url example --%>
<a href="<c:url value="${requestScope.url }"></c:url>">JournalDev</a>
</body>
</html>

Now when we run application with URL https://localhost:8080/JSTLExample/HomeServlet, we get response as in below image. JSTL, JSTL Example, JSTL Tutorial In above JSTL example, we are using c:catch to catch the exception within the JSP service method, it’s different from the JSP Exception Handling with error pages configurations. That’s all for a quick roundup of JSTL tags and example of JSTL core tags usage. Reference: JSTL Wikipedia Page

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 21, 2019

How to reverse a number in jstl?

- Div Anand

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 28, 2019

    Nice example. I could run on browser.

    - Manisha

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 19, 2018

      why the emp data cannot be display, as if the requestScope does not connected to HomeServlet. Regards.

      - FIFDIL MAJIWAN

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 27, 2018

        Hi, I have a doubt…what is the use of $ in the above statement and why we need this. And one more thing$(pageContext.request)… Please help me what is the usage and why ?

        - Srikanth

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          November 7, 2016

          how are you able to access private members of the Employee class through your JSP page using JSTL core tag library?

          - Laksh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 16, 2016

            Brilliant! Thank you so much

            - Sergii

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 29, 2016

              Great tutorial thank you so much

              - Irshad

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 1, 2016

                As always great tutorial, thank you, thank you!

                - aseem sharma

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 29, 2015

                  JSTL tags don’t evaluate if I import not able to use tags in hello.jsp ,it asking to add lib in hello.jsp also

                  - kripal

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 16, 2014

                    Thank for your tutorial. In my opinion, we use javax.servlet.jsp.jstl-1.2.1.jar, not jstl.jar .

                    - DoVy

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.