Popular Searches
Popular Course Categories
Popular Courses

Introduction to JSTL (JSP Standard Tag Library)

Introduction to JSTL (JSP Standard Tag Library)

JSP Expression Language, JSTL, and Custom Tags

Introduction to JSTL (JSP Standard Tag Library)

Course: Advanced Java Training

Topic: Introduction to JSTL (JSP Standard Tag Library)

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to JSTL

JSTL stands for JSP Standard Tag Library. It provides a collection of standard tags that simplify common tasks in JavaServer Pages (JSP), including conditional processing, iteration, output formatting, internationalization, URL handling, and string manipulation.

Without JSTL, developers often use Java scriptlets inside JSP pages to implement loops, conditions, and other presentation logic. JSTL provides a cleaner tag-based alternative, making JSP files easier to read, maintain, and understand.

For example, instead of writing a Java loop inside a JSP page, developers can use the JSTL <c:forEach> tag to display a collection of products.

Example

<c:forEach var="product" items="${products}">
    <p>${product.name}</p>
</c:forEach>

This code iterates over a collection named products and displays each product's name. The collection is normally prepared by a Servlet or controller before forwarding the request to the JSP page.

2. Learning Objectives

After completing this topic, you should be able to:

  • Define JSTL and explain its purpose in JSP development.
  • Understand the relationship between JSP, JSTL, and Expression Language (EL).
  • Identify the major JSTL tag libraries and their purposes.
  • Declare a tag library in a JSP page.
  • Use core tags for conditions, loops, variables, and output.
  • Understand formatting tags, functions, URL handling, and legacy XML and SQL tag libraries.
  • Integrate JSTL with Servlets and JavaBeans.
  • Identify common configuration problems and apply best practices.

3. Why Do We Need JSTL?

JSP supports embedding Java code in web pages, but placing too much Java code inside HTML can make applications difficult to maintain. JSTL helps separate presentation from application logic by providing reusable tags for common tasks.

Problems Without JSTL

  • Java scriptlets can mix business logic with HTML markup.
  • Complex loops and conditions can make pages difficult to read.
  • Repeated formatting and output logic can create duplicated code.
  • Developers may implement similar presentation tasks differently across pages.
  • Testing and maintaining JSP views becomes more difficult as the application grows.

Benefits of JSTL

  • Readable JSP pages: Tag-based syntax is easier to follow alongside HTML.
  • Less scriptlet code: Common presentation tasks can be handled without embedded Java statements.
  • Standardized behavior: Standard tags have consistent meanings across compatible implementations.
  • Integration with EL: Tags can evaluate expressions such as ${user.name}.
  • Better separation of concerns: Servlets and services prepare data while JSP and JSTL display it.
  • Reusable patterns: The same tag structures can be used across multiple JSP pages.

4. What Is a Tag Library?

A tag library is a collection of tags that provide predefined functionality to a JSP page. A tag library has an associated identifier or URI, and the JSP page declares it using a taglib directive.

Each tag library is generally assigned a prefix. The prefix is used before tag names to identify which library provides the tag.

Example of a Taglib Directive

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

In this declaration:

  • <%@ taglib ... %> declares a tag library for the JSP page.
  • prefix="c" assigns the prefix c to the library.
  • uri="jakarta.tags.core" identifies the modern Jakarta Standard Tag Library core library.

The prefix is a local name chosen in the JSP page. The URI identifies the tag library and must match the library provided by the application's JSTL version.

5. Main JSTL Tag Libraries

JSTL is organized into functional groups. The tag libraries available and their URIs depend on the JSTL version used by the application. The following table shows the common groups.

Tag Library Common Prefix Purpose
Core c Variables, output, conditions, iteration, URL operations, and flow control.
Formatting and Internationalization fmt Locale-sensitive messages, dates, numbers, and currency formatting.
Functions fn String and collection-related functions, such as checking string length or replacing text.
XML Processing x XML parsing, selection, and transformation-related operations in versions that provide this library.
SQL sql Basic database-related tags, mainly for demonstrations and simple examples.

Important: For modern Jakarta Tags 3.x applications, the core, formatting, functions, XML, and SQL library URIs use the jakarta.tags.* naming pattern. Older JSTL applications commonly use URIs beginning with http://java.sun.com/jsp/jstl/. Always match the URI and dependency to the application environment.

6. Configuring JSTL in a Java Web Application

To use JSTL tags, the web application must have a compatible JSP container and JSTL API and implementation available. The exact dependency depends on whether the project uses the older Java EE namespace or the newer Jakarta EE namespace.

Step 1: Identify the Application Environment

  • Legacy applications may use Java EE, JSP 2.x, and JSTL 1.2.
  • Jakarta EE applications use the jakarta.* namespace for the relevant APIs.
  • JSTL 3.0 uses the newer jakarta.tags.* tag library URIs.
  • Check the servlet container, JSP version, Java version, and dependency compatibility before adding a library.

Step 2: Add the Compatible JSTL Dependency

For a Maven application targeting Jakarta Tags 3.0, the API dependency can be declared as follows. Ensure that a compatible JSTL implementation is also available in the runtime; the exact dependency arrangement depends on the chosen implementation and server.

<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>3.0.2</version>
</dependency>

This API dependency alone may not provide the tag implementation. Follow the chosen implementation's installation instructions and avoid bundling conflicting versions of the same JSTL libraries.

Step 3: Declare the Core Library

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

For a legacy JSTL 1.2 application, the directive is commonly written as:

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

Step 4: Use a JSTL Tag

<c:set var="courseName" value="Advanced Java" />
<p>Course: ${courseName}</p>

If the application is configured correctly, the page evaluates the tag and displays the assigned value.

7. Core JSTL Tags

The core library is one of the most commonly used parts of JSTL. It supports variable handling, conditional rendering, iteration, output, and URL operations.

7.1 The c:out Tag

The <c:out> tag evaluates a value and writes the result to the response. It can also escape XML-sensitive characters when its default escaping behavior is enabled.

<c:out value="${user.name}" default="Guest" />

If user.name is unavailable, the default value can be displayed.

For ordinary HTML text, output escaping is important when displaying untrusted values. Escaping with c:out is not a universal solution for JavaScript, CSS, URL, or other output contexts; choose context-appropriate encoding.

7.2 The c:set Tag

The <c:set> tag stores a value in a scoped variable or sets a property of a supported target object.

<c:set var="discount" value="10" />
<p>Discount: ${discount}%</p>

By default, the variable is stored in page scope. The scope attribute can specify page, request, session, or application.

<c:set var="message" value="Welcome!" scope="request" />

7.3 The c:remove Tag

The <c:remove> tag removes a scoped variable.

<c:remove var="message" scope="request" />

When the scope is omitted, the tag removes the matching variable from the page scope.

7.4 The c:if Tag

The <c:if> tag evaluates a condition and processes its body when the condition is true.

<c:if test="${marks ge 40}">
    <p>Result: Pass</p>
</c:if>

The expression uses EL to check whether the marks are greater than or equal to 40.

7.5 The c:choose, c:when, and c:otherwise Tags

These tags implement multiple conditional branches. They are useful when a page needs to display different output for different conditions.

<c:choose>
    <c:when test="${marks ge 75}">
        <p>Grade: Distinction</p>
    </c:when>
    <c:when test="${marks ge 40}">
        <p>Grade: Pass</p>
    </c:when>
    <c:otherwise>
        <p>Grade: Needs Improvement</p>
    </c:otherwise>
</c:choose>

The first matching c:when branch is used. If no branch matches, the c:otherwise body is processed.

7.6 The c:forEach Tag

The <c:forEach> tag repeats its body for each item in a collection or over a specified range.

<c:forEach var="student" items="${students}">
    <p>${student.name}</p>
</c:forEach>

The collection is usually placed in a request attribute by a Servlet or controller. The var attribute names the variable representing the current item.

A numeric range can also be used:

<c:forEach var="i" begin="1" end="5">
    <p>Number: ${i}</p>
</c:forEach>

7.7 The c:forTokens Tag

The <c:forTokens> tag iterates over tokens in a string separated by specified delimiters.

<c:forTokens items="Java,Servlets,JSP,JSTL"
             delims=","
             var="topic">
    <p>${topic}</p>
</c:forTokens>

7.8 The c:url and c:param Tags

The <c:url> tag constructs a URL. The <c:param> tag adds a parameter and handles the encoding of its name and value according to the tag's rules.

<c:url var="searchUrl" value="/search">
    <c:param name="keyword" value="${searchKeyword}" />
</c:url>

<a href="${searchUrl}">Search</a>

Use the appropriate context path and ensure the resulting link is valid for the application. Do not treat URL construction as a replacement for input validation or authorization.

7.9 The c:redirect Tag

The <c:redirect> tag sends a redirect response to another URL.

<c:redirect url="/login.jsp" />

Redirects should be used carefully. In MVC applications, redirect decisions are often best handled by the Servlet controller rather than being embedded in a view.

7.10 The c:catch Tag

The <c:catch> tag catches a throwable raised while its body is evaluated and can expose it as a scoped variable.

<c:catch var="pageError">
    <!-- Place a small operation that may fail here -->
</c:catch>

<c:if test="${not empty pageError}">
    <p>The requested operation could not be completed.</p>
</c:if>

Do not use c:catch to hide serious application failures or replace proper logging and exception handling in the backend.

8. Formatting and Internationalization Tags

The formatting library uses the fmt prefix in common JSTL examples. It supports locale-sensitive message, number, and date formatting.

8.1 Formatting Numbers

<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>

<fmt:formatNumber value="${product.price}"
                  type="number"
                  minFractionDigits="2" />

This formats a numeric value according to the tag's formatting rules. Currency formatting should specify an appropriate currency code and locale when needed.

8.2 Formatting Currency

<fmt:formatNumber value="${product.price}"
                  type="currency"
                  currencyCode="INR" />

The rendered currency symbol and number presentation can depend on locale and runtime configuration.

8.3 Formatting Dates

<fmt:formatDate value="${order.orderDate}"
                pattern="dd-MM-yyyy" />

The date value must be of a type supported by the tag and its implementation. Confirm the expected date type when working with modern Java date/time APIs.

8.4 Internationalized Messages

Applications can store messages in resource bundles and display them using formatting tags. This makes it easier to present text in multiple languages without duplicating the page layout.

<fmt:setLocale value="en_IN" />
<fmt:bundle basename="messages">
    <fmt:message key="welcome.message" />
</fmt:bundle>

The corresponding resource bundle must be available on the application's classpath and contain the specified key.

9. JSTL Functions

The functions library provides utilities for common string and collection operations. It is commonly declared with the fn prefix.

<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
Function Purpose Example
fn:length() Returns the length of a string or supported collection ${fn:length(students)}
fn:contains() Checks whether a string contains a substring ${fn:contains(title, "Java")}
fn:startsWith() Checks a string prefix ${fn:startsWith(code, "ADV")}
fn:endsWith() Checks a string suffix ${fn:endsWith(fileName, ".jsp")}
fn:toUpperCase() Converts a string to uppercase ${fn:toUpperCase(name)}
fn:toLowerCase() Converts a string to lowercase ${fn:toLowerCase(name)}
fn:trim() Removes leading and trailing whitespace ${fn:trim(keyword)}
fn:replace() Replaces occurrences of a substring ${fn:replace(title, "JSP", "Jakarta Pages")}
fn:substring() Extracts part of a string ${fn:substring(title, 0, 5)}
fn:join() Joins array or collection values where supported by the function signature ${fn:join(topics, ", ")}

Example: Counting Students

<p>Total students: ${fn:length(students)}</p>

Functions are useful for simple presentation-related transformations. Complex data processing should generally be performed in application code.

10. XML and SQL Tag Libraries

10.1 XML Tags

JSTL versions that include the XML library provide tags for working with XML data, selecting nodes, and processing XML content. These tags use the x prefix in standard examples.

<%@ taglib prefix="x" uri="jakarta.tags.xml" %>

XML tag functionality is version-dependent and should be used only when the corresponding library is present. For complex XML processing, dedicated Java XML APIs or application services may be more suitable.

10.2 SQL Tags

JSTL has also provided SQL tags for basic database examples. They can demonstrate simple database interactions, but they are generally not recommended for production application architecture.

<%@ taglib prefix="sql" uri="jakarta.tags.sql" %>

Production applications should normally access databases through DAO or repository classes and service layers, using appropriate connection management and parameterized queries. Database credentials and query logic should not be embedded in JSP presentation pages.

11. Integrating JSTL with Servlets

A common Java web application pattern is to use a Servlet as a controller, JavaBeans or model objects to represent data, and JSP with JSTL to render the result. This approach supports separation of concerns and keeps the view focused on presentation.

Step 1: Create a JavaBean

public class Student {
    private String name;
    private int marks;

    public Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    public String getName() {
        return name;
    }

    public int getMarks() {
        return marks;
    }
}

Step 2: Prepare Data in a Servlet

import java.io.IOException;
import java.util.Arrays;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/students")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        var students = Arrays.asList(
            new Student("Aarav", 85),
            new Student("Priya", 72),
            new Student("Kabir", 38)
        );

        request.setAttribute("students", students);
        request.getRequestDispatcher("/WEB-INF/views/students.jsp")
               .forward(request, response);
    }
}

Step 3: Display the Data with JSTL

<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
    <title>Student List</title>
</head>
<body>
    <h1>Student Results</h1>

    <c:choose>
        <c:when test="${empty students}">
            <p>No student records found.</p>
        </c:when>
        <c:otherwise>
            <ul>
                <c:forEach var="student" items="${students}">
                    <li>
                        <c:out value="${student.name}" /> -
                        <c:out value="${student.marks}" />
                        <c:choose>
                            <c:when test="${student.marks ge 40}">
                                (Pass)
                            </c:when>
                            <c:otherwise>
                                (Needs Improvement)
                            </c:otherwise>
                        </c:choose>
                    </li>
                </c:forEach>
            </ul>
        </c:otherwise>
    </c:choose>
</body>
</html>

This example demonstrates the MVC approach: the Servlet prepares the student list, and the JSP uses JSTL to handle iteration, conditions, and output. The JSP is placed under WEB-INF so it can be accessed through the controller rather than requested directly.

12. JSTL vs JSP Scriptlets

Feature JSTL Scriptlets
Syntax Tag-based markup Java code inside JSP delimiters
Loops <c:forEach> Java for or while statements
Conditions <c:if> and <c:choose> Java if and else
Maintainability Generally cleaner for presentation logic Can mix application logic with markup
Recommended usage Common view-layer operations Avoid in new JSP pages where alternatives exist

13. JSTL vs JSP Expression Language (EL)

JSTL and EL are complementary technologies, not direct replacements for one another.

Feature JSTL Expression Language
Main role Provides tags for iteration, conditions, formatting, and URL operations Evaluates expressions and accesses attributes and properties
Example <c:forEach items="${students}" var="s"> ${student.name}
Use together? Yes, JSTL tags commonly use EL expressions as their values Yes, EL supplies values and conditions to many JSTL tags

14. Common JSTL Errors and Troubleshooting

Error or Symptom Possible Cause Solution
Taglib URI not recognized URI does not match the JSTL version Use the correct legacy or Jakarta URI for the installed library.
JSTL tags are not found Missing API or implementation dependency Verify the dependency and ensure a compatible implementation is available at runtime.
EL appears as literal text EL is disabled or the JSP is not processed correctly Check JSP configuration, directives, and server behavior.
Loop produces no output Collection is null, empty, or stored under a different attribute name Confirm the controller sets the attribute before forwarding.
Bean property is blank Incorrect property name or missing getter Check the JavaBean and its public getter methods.
Formatting tag fails Unsupported value type or incorrect format attributes Confirm the value type and tag syntax.
Class loading conflict Multiple incompatible JSTL versions are present Remove conflicting libraries and align dependencies with the container.
Redirect does not behave as expected Incorrect target URL or response already committed Verify the target and consider handling navigation in the controller.

15. JSTL Best Practices

  • Use JSTL and EL for common view-layer operations instead of embedding Java scriptlets.
  • Keep business rules, authorization checks, and database operations in backend components.
  • Prepare data in Servlets or controllers before forwarding to JSP pages.
  • Use descriptive variable names and explicit scopes where appropriate.
  • Use c:out for ordinary HTML text output when escaping is required, and apply context-specific encoding for other contexts.
  • Validate user input on the server, regardless of how the data is displayed.
  • Use a compatible JSTL API and implementation for the JSP container and Jakarta or Java EE version.
  • Avoid embedding database credentials or production SQL logic in JSP files.
  • Handle empty collections and missing values gracefully.
  • Keep JSP pages focused on rendering and presentation.

16. Practical Exercises

  1. Welcome Page: Use c:set to define a message and display it with EL.
  2. Conditional Display: Use c:if to show a message when a user's marks meet a passing threshold.
  3. Multiple Conditions: Use c:choose, c:when, and c:otherwise to display student grades.
  4. Student List: Create a Servlet that passes a list of Student objects to a JSP page. Display the list with c:forEach.
  5. Empty Data Handling: Use the EL empty operator to show a message when the list contains no records.
  6. URL Creation: Use c:url and c:param to construct a search link.
  7. Number Formatting: Use fmt:formatNumber to display product prices.
  8. String Functions: Use fn:length, fn:contains, and fn:toUpperCase in a JSP page.

17. Mini Project: Student Result Management View

Objective: Create a small JSP application that displays student records and results using JSTL and EL.

Requirements

  • Create a Student JavaBean with ID, name, course, and marks properties.
  • Build a Servlet that prepares a list of student objects.
  • Store the list in request scope and forward the request to a JSP page.
  • Use c:forEach to display the student records.
  • Use c:choose to display a result or grade for each student.
  • Use c:out where appropriate to escape ordinary HTML text output.
  • Handle an empty list with a suitable message.
  • Keep data access and business rules outside the JSP view.

Expected Outcome

The completed application should render a student result table or list, display grades conditionally, and handle missing data gracefully. It should demonstrate how a Servlet, JavaBean, JSTL, and EL work together in a maintainable Java web application.

18. Interview Questions and Answers

Q1. What is JSTL?

Answer: JSTL stands for JSP Standard Tag Library. It provides standard tags for common JSP tasks, such as iteration, conditional processing, output, formatting, and URL handling.

Q2. Why is JSTL used in JSP?

Answer: JSTL reduces the need for Java scriptlets and makes presentation logic easier to read, maintain, and reuse.

Q3. What is a taglib directive?

Answer: A taglib directive declares a tag library in a JSP page and assigns it a prefix that is used to reference the library's tags.

Q4. What does the c:forEach tag do?

Answer: It iterates over supported collections or a specified range, allowing the JSP page to render repeated content.

Q5. What is the difference between c:if and c:choose?

Answer: c:if processes a body when a condition is true. c:choose supports multiple mutually exclusive branches through c:when and an optional c:otherwise.

Q6. What is the purpose of c:out?

Answer: It evaluates a value and writes it to the response, with optional default output and XML-sensitive character escaping.

Q7. What is the difference between JSTL and EL?

Answer: JSTL provides tags for common page operations, while EL evaluates expressions and retrieves values. They are commonly used together.

Q8. What is the purpose of the fmt library?

Answer: It supports locale-sensitive formatting, including dates, numbers, currencies, and internationalized messages.

Q9. What is the purpose of the fn library?

Answer: It provides functions for string and collection operations, such as length checks, substring extraction, and text conversion.

Q10. Should JSTL SQL tags be used in production applications?

Answer: They are generally not recommended for production architecture. Database operations should normally be handled in DAO or repository classes and service layers.

Q11. Why might a JSTL tag not be recognized?

Answer: Common causes include a missing library, incompatible dependencies, an incorrect taglib URI, or a mismatch between the JSTL version and the JSP container.

Q12. What is the difference between legacy JSTL URIs and Jakarta Tags URIs?

Answer: Older applications commonly use URIs such as http://java.sun.com/jsp/jstl/core, while modern Jakarta Tags 3.x applications use URIs such as jakarta.tags.core.

19. Quick Revision Checklist

  • JSTL means JSP Standard Tag Library.
  • JSTL provides standard tags for common presentation tasks.
  • The taglib directive declares a tag library and its prefix.
  • The core library commonly uses the prefix c.
  • c:if handles simple conditions.
  • c:choose, c:when, and c:otherwise handle multiple branches.
  • c:forEach iterates over collections and ranges.
  • c:set assigns scoped variables, and c:remove removes them.
  • c:out writes evaluated output and can escape XML-sensitive characters.
  • The fmt library supports formatting and internationalization.
  • The fn library provides string and collection functions.
  • JSTL works closely with JSP Expression Language.
  • Use a library URI and implementation compatible with the application environment.
  • Keep database access and business logic out of JSP views.

20. Conclusion

JSTL is an important part of JSP development because it provides a standardized way to perform common presentation tasks without embedding extensive Java code in web pages. Its core tags support conditions, loops, variable handling, and URL operations, while other libraries provide formatting and string utilities.

By combining JSTL with Expression Language, JavaBeans, and Servlet controllers, developers can build cleaner and more maintainable web applications. Practice the examples and exercises in this topic to strengthen your understanding of JSP-based application development.


Further Learning

Explore the Advanced Java Training Course to learn more about Servlets, JSP, JSTL, JDBC, Hibernate, and enterprise Java development.

To learn about the course or request a demonstration, visit the JustAcademy Course Demo Registration Page.

Visit the JustAcademy official website for additional training resources.

Reference Documentation

Previous Next
whatsapp