JSP Standard Tag Library(JSTL) in JSP

In the previous article, we learn How Exception is handled on the JSP page. In this article, we will discuss JSTL which is the JSP Standard Tag Library.

Java Server Pages Standard Tag Library is a library of different tags that will make Our JSP coding easier. In this article, we will cover what is JSTL, the classification of JSTL, and the Advantages of using JSTL.

What is JSTL?

JSTL acronym to Java Server Pages Standard Tag Library. It is a collection of tags that simplify web development. It consists of a wide variety of tags that fit into discrete functional areas. In order to use JSTL, we need to install the JSTL library. Follow the below steps to set up JSTL:

  • first, download the binary distribution from https://tomcat.apache.org/taglibs/index.html here.
  • unzip the file.
  • To use JSTL just copy the jar files in the distribution lib directory to your project webapps\root\WEB-INF\lib directory.

Core Tags

The core Tags are the commonly used tags in JSP.  We can use core tags for iteration, conditional logic, catch the exception, URL forward, redirect, etc. To use core tags we need to include the JSTL library in JSP.

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

Here, the prefix is used to define all the core tags (‘c’ is used as a prefix here). and URI is the library.

Following is the list of core JSTL tags.

  • <c: out>: It shows the result of an expression.
  • <c: import>: It retrieves the URI and exposes content to either page or Reader.
  • <c: url> : It creats the URL for optional query parameter.
  • <c: redirect> : It redirect us to new page.
  • <c: param>: It adds a parameter to a containing import’s tag.
  • <c: forTokens>: It iterates over tokens.
  • <c: forEach>: It is for iterating the collection of data.
  • <c: choose>: It is a simple conditional tag that includes its body content if the evaluated condition is true.
  • <c: when>: It is a subtag of <c: choose> that includes the body when the condition is true.
  • <c: otherwise>: It is a subtag of <c: choose> that includes the body when the condition is false.
  • <c: if>: It is a simple conditional tag.
  • <c: catch>: It catches the exception thrown by the body.
  • <c: remove>: It removes the scoperd varibale.
  • <c: set>: It sets the result of an expression.

We will take a  simple example that will demonstrate the use of some of these tags given above. We will  learn how to use <c:choose>, <c: when>, and <c:otherwise>.

Syntax for <c:choose>, <c: when> and <c:otherwise>

<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

Student.java

package com.abc;

public class Student {
  private String name;
  private String lastName;
  private boolean likeIceCream;

  public Student(String name, String lastName, boolean likeIceCream) {
    super();
    this.name = name;
    this.lastName = lastName;
    this.likeIceCream = likeIceCream;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getLastName() {
    return lastName;
  }

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

  public boolean isLikeIceCream() {
    return likeIceCream;
  }

  public void setLikeIceCream(boolean likeIceCream) {
    this.likeIceCream = likeIceCream;
  }

}

iterate.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
<%@ page import="java.util.*, com.abc.Student" %>
    
 <%@ 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">
<%
List<Student> list=new ArrayList();
list.add(new Student("Monica","Geller",false));
list.add(new Student("Ross","Geller",false));
list.add(new Student("Rachel","Green",true));
list.add(new Student("Joey","Tribbiani",true));
list.add(new Student("Phoebe","Buffay",false));
list.add(new Student("Chandler","Bing",false));
pageContext.setAttribute("students1", list);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>


<body bgcolor="#A5D8F3">
<h3>Use of JSTL Tags</h3>
<table border="1" cellpadding="2">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Likes Ice cream</th>
</tr>
<c:forEach var="temp" items="${students1}">
<tr>
<td>${temp.name}</td>
<td>${temp.lastName}</td>
<td>
<c:choose>
<c:when test="${temp.likeIceCream}">
Likes Icecream!!!
</c:when>
<c:otherwise>
doesn't like Icecream!!!
</c:otherwise>
</c:choose>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>

output

Formatting Tags

The formatting tags are useful for formatting and displaying text, date, time. The URL for formatting tags is http://java.sun.com/jsp/jstl/fmt. The syntax for including JSTL in JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"  %>

Here, the prefix is used to define all the formatting tags (‘fmt’ is used as a prefix here). and URI is the library.

Following is the list of Formatting Tags

  • <fmt:parseNumber>: It is used to parse the string representation of currency, number.
  • <fmt: timeZone>: It specifies the time zone for formatting.
  • <fmt:formatNumber>: It is used to format the numerical value with a specific format.
  • <fmt:parseDate>: It parses the string representation of a time and date.
  • <fmt: bundle>: It is used for creating the ResourceBundle objects which will be used by their tag body.
  • <fmt:setTimeZone>: It stores the time zone inside a time zone configuration variable.
  • <fmt:setBundle>: It loads the resource bundle and stores it in a bundle configuration variable or the named scoped variable.
  • <fmt:message >:It displays an internationalized message.
  • <fmt:formatDate>: It formats the time, date using some pattern and styles.

SQL Tags

These SQL tags provide tags that help us to connect with a database such as Oracle, SQL Server, etc. The URL for SQL tags is http://java.sun.com/jsp/jstl/sql. The Syntax for including the JSTL SQL tag in JSP is:

<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>

Here, the prefix is used to define all the SQL tags (‘sql’ is used as a prefix here). and URI is the library.

Following is the list of SQL Tags

  • <sql:setDataSource>: It is used for creating a simple data source suitable only for prototyping.
  • <sql: query>: It is used for executing the SQL query.
  • <sql: update>: It is used for executing the SQL update.
  • <sql: param>: It is used for sets the parameter in an SQL statement to the specified value.
  • <sql:dateParam>: It is used for sets the parameter in an SQL statement to a specified java.util.Date value.
  • <sql: transaction>: It is used to provide the nested database action with a common connection.

XML tags

The JSTL provides XML tags for manipulating or updating the XML file in the project. The URL for the XML tag is http://java.sun.com/jsp/jstl/xml. The Syntax for including XML tag in JSP is:

<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

Here, the prefix is used to define all the XML tags (‘xml’ is used as a prefix here). and URI is the library.

Following is the list of  XML tags

  • <x:out>: It is like <%= … > tag, but for XPath expressions.
  • <x: parse>: It is used to parse the XML data specified.
  • <x: set>: It is used to sets a variable to the value of an XPath expression.
  • <x: choose>: It is a conditional tag that establishes a context for conditional operations.
  • <x: when>: It is a subtag of that will include its body if the condition evaluated be ‘true’.
  • <x: otherwise>: It is subtag of that follows tags and runs only if all the prior conditions evaluated be ‘false’.
  • <x: if>: It is used for evaluating the test XPath expression and if it is true, it will process its body content.
  • <x:transform>: It is used in an XML document for providing the XSL(Extensible Stylesheet Language) transformation.
  • <x: param>: It is used along with the transform tag for setting the parameter in the XSLT style sheet.

JSTL Functions

JSTL functions have many functions available. The URL for the JSTL function is http://java.sun.com/jsp/jstl/functions. The Syntax for including JSTL function is:

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

Here, the prefix is used to define all the JSTL functions (‘fn’ is used as a prefix here). and URI is the library.

Following is the list of JSTL functions

  • <fn: contains()>: It checks whether a string contains the specified substring.
  • <fn: endsWith()>: It checks whether a string end with a specified string.
  • <fn: escapeXml()>: It escapes character that are interpreted as XML.
  • <fn: indexOf()>: It returns the index of specified char in string.
  • <fn:join()>: It Joins the string into an array.
  • <fn: length()>: It returns the number of characters in string.
  • <fn: replace()>: It replaces a string with specified string.
  • <fn: spli()>: It splits the string.
  • <fn:startsWith()>: It checks whether input string starts with specified char.
  • <fn:subString()>: It returns subset of string.
  • <fn:substringAfter()>: It returns the subset of string followed by specified string.
  • <fn:substringrBefore()>: It returns the subset of string before a specified string.
  • <fn: toLowerCase()>: It converts the string into lowercase.
  • <fn: toUpperCase()>: It converts the string into uppercase.
  • <fn:trim()>: It removes whitespaces.

Advantages of JSTL

  • It has a standard tag that helps the developer to understand the code.
  • It makes the code neat and clean,
  • It handles JAVA bean code easily.
  • As it is based on XML, it is easy for the developer to understand the code.
  • It is used for code reusability( we can use JSTL tags on various pages).
  • It avoids using Scriptlet tags.

Thus, this was all about the JSTL i.e Java Server Pages Standard Tag Library.

In the next article of this tutorial, we will cover all the custom tags available on the JSP page with a simple example.