JSTL Tutorial, JSTL Tags Example

Filed Under: Java EE

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 "http://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="http://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="http://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="http://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="http://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="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    

Note that all the JSTL standard tags URI starts with http://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" "http://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="http://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 http://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

Comments

  1. Div Anand says:

    How to reverse a number in jstl?

  2. Manisha says:

    Nice example. I could run on browser.

  3. FIFDIL MAJIWAN says:

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

  4. Srikanth says:

    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 ?

  5. Laksh says:

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

  6. Sergii says:

    Brilliant! Thank you so much

  7. Irshad says:

    Great tutorial thank you so much

    1. Pankaj says:

      you are welcome Irshad.

  8. aseem sharma says:

    As always great tutorial, thank you, thank you!

    1. Pankaj says:

      glad you liked it. 🙂

  9. kripal says:

    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

  10. DoVy says:

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

    1. John Mark Isaac Madison says:

      When you say javax.servlet.jsp.jstl

      Do you mean:
      javax.servlet.jsp.jstl-api.jar
      and
      jstl-api.jar
      and
      jstl.jar

      Because on the maven repository I don’t see anything called
      javax.servlet.jsp.jstl-1.2.1.jar

      However, I do see that the page is titled:
      javax.servlet.jsp.jstl

      http://mvnrepository.com/artifact/javax.servlet.jsp.jstl

  11. chavda pradipsinh says:

    here,how can this uri=”http://java.sun.com/jsp/jstl/core” find without internet connection.I confused..

    1. Aditya says:

      If u open the jar file u vl find the tld file. If you view the file the uri is given as http://java.sun.com/jsp/jstl/core so we use the same uri to link it.

  12. Amrutha says:

    function Total() {
    var tbody = document.getElementById(“purchaseItems”);

    for (var i = 0; i < tbody.rows.length; i++) {
    alert("inside for loop");
    var qty = document.getElementsByClassName('qty').value;
    alert("quantity"+qty);
    var price = document.getElementsByClassName('price').value;
    alert("price"+price);
    var answer = (Number(qty) * Number(price)).toFixed(2);
    alert("total"+answer);
    document.getElementsByClassName('totalprice[' + i + ']').value = answer;
    }
    }
    this is my javascript code for getting the total

  13. Amrutha says:

    Hi , i have a jsp page in which i am implementing dynamic add rows code using jquery javascript but i am not able to multiply the values of it….pls suggest a solution

  14. vivek says:

    Can somebody tell me syntax for:

    String userId = request.getParameter(“USER_ID”);

  15. Satyam Bansal says:

    Hi ,

    Please help me in this ,I have a condition as given below:
    1. I have send a list of one class ‘A’ to my jsp. —> List l = new ArrayList()
    2. that list have value of class ‘B’ .
    3. In that Class B , I have two variable of type String , List. Here C is another class .
    4. Class C has variables in String.
    I have to display all variables of Class C and String variable of Class B on my jsp.
    how to do it? Please help . need it urgent.

    Thanks in Advance.

    -Satyam

    1. Satyam Bansal says:

      all list have < and > in above condition . Class B has list < C >.

    2. Pankaj says:

      We can use JSTL tags to iterate through the list, for nested variables, create a variable first and assign it from the object list, then iterate it for clarity.

  16. Zura Maisuradze says:

    hello @Pankaj. if i add those records and then other 2 records will both tables appear? or just one

    1. Pankaj says:

      I am not sure what you meant here.

  17. Pranay says:

    Hi
    it works properly .
    very good for beginners.

    Thanks………….

  18. naveen says:

    In JSTL 1.0 version i want to compare the string values. how i can do it….

  19. webuser says:

    Page is not getting forwarded after setting request.setattribute. values.

    1. Pankaj says:

      i didn’t get you, could you please share the code?

  20. Nagaraju says:

    Hi Pankaj,

    Thanks for your posting. can you tell me the difference between the core jstl tags and xml jstl tags.

    Thanks in advance.

  21. jsp learner says:

    You gave the example for eclipse,can you please tell me how to do in tomcat.In tomcat/webapps folder,its not working.Please give an example how to do in tomcat

    1. Pankaj says:

      Even if I am running in Eclipse, the runtime environment is Tomcat 7 and it will work there too. Please check the tomcat version you are using.

  22. Anastasia says:

    Do you know how to use tag if I want to compare 2 strings?
    I have the example with inheritance and I need to check the type of element before output.

    Please, explain why doesn`t it work?

    1. Pankaj says:

      I think your code didn’t get posted, please post again.

  23. ye ko says:

    very good ,congratulations

  24. Harinath says:

    how to put download option to download table data in “csv” or “Excelsheet” format

    1. Pankaj says:

      That would require processing at server side to create the CSV file and then send it as server response with MIME-TYPE as “application/octet-stream” and we need to set “Content-Disposition” header with value as “attachment; filename=”fileName“.

      Check a quick tutorial at https://www.journaldev.com/1964/servlet-upload-file-and-download-file-example

  25. chanchal says:

    this code not working in my tomcat 6.0.
    Employee table

    ID Name Role
    $ {emp.getId()} $ {emp.getName()} $ {emp.getRole()}
    getting this output everytime

    1. Pankaj says:

      Can you check with Tomcat 7? I have tested all these on Java 7 installation.

  26. sat says:

    Hi Pankaj,
    your tutorials are great.I am getting this error.Plz help me to figure out of this problem.I am waiting for the response from you.

    java.util.logging.ErrorManager: 4
    java.io.FileNotFoundException: C:\Program Files\apache-tomcat-7.0.27\logs\catalina.2013-08-29.log (Access is denied)

    1. Pankaj says:

      Check if the file is present and the user has access to it.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages