JSTL in JSP

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 273 of 306

JSTL in JSP (the Jakarta Standard Tag Library) gives you ready-made tags for loops, conditions, URLs, number and date formatting, and string functions. With JSTL a JSP page needs no Java scriptlets at all: logic is written as clean, HTML-like tags that designers and developers can both read.

This lesson sets up JSTL 3.0 on Tomcat 11 and walks through the core, formatting and function tags with a small example for each. It ends with a searchable course list page. The examples continue the student-portal app from JSP in Java.


Add JSTL to Your Project

Tomcat does not ship JSTL, so add the API and an implementation to your pom.xml. They must be packaged in the WAR (default compile scope).

<dependencies>
    <!-- Jakarta Standard Tag Library 3.0 API -->
    <dependency>
        <groupId>jakarta.servlet.jsp.jstl</groupId>
        <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
        <version>3.0.2</version>
    </dependency>
    <!-- Implementation (from the GlassFish project) -->
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jakarta.servlet.jsp.jstl</artifactId>
        <version>3.0.1</version>
    </dependency>
</dependencies>

Then declare the libraries you need at the top of each JSP:

LibraryDirectiveCommon prefixUsed for
Core<%@ taglib prefix="c" uri="jakarta.tags.core" %>cOutput, variables, conditions, loops, URLs
Formatting<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>fmtNumbers, currency, dates, locales
Functions<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>fnString helpers inside EL
mvn -q package
unzip -l target/student-portal.war | grep -i jstl

Output:

    46186  2026-11-18 11:00   WEB-INF/lib/jakarta.servlet.jsp.jstl-api-3.0.2.jar
   423751  2026-11-18 11:00   WEB-INF/lib/jakarta.servlet.jsp.jstl-3.0.1.jar

How it works:

  • The two JARs land in WEB-INF/lib, where Tomcat finds them at runtime. Dependency scopes are explained in Maven Dependencies.
  • JSTL 3.0 introduced the short jakarta.tags.* URIs. Older tutorials use http://java.sun.com/jsp/jstl/core with the javax version, which does not work on Tomcat 10 and later.
  • The JAR sizes on your machine may differ slightly.

<c:out> prints a value and escapes HTML by default, which protects pages from script injection. Plain ${...} does not escape.

AttributeMeaning
valueThe expression to print
defaultText shown when the value is null
escapeXmltrue (default) converts <, >, &, ', " to entities
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<p>Raw EL:   ${param.comment}</p>
<p>c:out:    <c:out value="${param.comment}"/></p>
<p>Nickname: <c:out value="${param.nickname}" default="(not set)"/></p>
curl "http://localhost:8080/student-portal/out-demo.jsp?comment=%3Cb%3EGreat%3C/b%3E%20%26%20clear"

Output:

<p>Raw EL:   <b>Great</b> & clear</p>
<p>c:out:    <b>Great</b> & clear</p>
<p>Nickname: (not set)</p>

How it works:

  • The raw EL line would make the browser render bold text, and could just as easily run a <script> tag.
  • c:out converts the special characters into entities, so the browser shows the comment exactly as typed.
  • default handles the missing nickname parameter without an if block.

Store and Remove Variables With c:set and c:remove

<c:set> creates a variable in a chosen scope. <c:remove> deletes it.

<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:set var="fee" value="4999"/>
<c:set var="discount" value="${fee * 0.10}"/>
<c:set var="courseName" scope="request">Java Programming</c:set>
Course: ${courseName}
Fee: ${fee}, discount: ${discount}, you pay: ${fee - discount}
<c:remove var="discount"/>
Discount after remove: [${discount}]
curl http://localhost:8080/student-portal/set-demo.jsp

Output:

Course: Java Programming
Fee: 4999, discount: 499.90000000000003, you pay: 4499.1
Discount after remove: []

How it works:

  • Without scope, c:set stores the variable in page scope. scope="request" makes it visible to included pages too.
  • The value can come from an attribute or from the tag body, as courseName shows.
  • 499.90000000000003 is normal floating-point rounding. Format money with fmt:formatNumber, shown later in this lesson.

Conditions With c:if and c:choose

<c:if> runs its body when test is true. <c:choose> with <c:when> and <c:otherwise> works like an if/else if/else chain.

<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:set var="marks" value="${empty param.marks ? 0 : param.marks}"/>
Marks: ${marks}
<c:if test="${marks >= 40}">Result: Pass</c:if>
<c:if test="${marks < 40}">Result: Fail</c:if>
<c:choose>
  <c:when test="${marks >= 90}">Grade: A</c:when>
  <c:when test="${marks >= 75}">Grade: B</c:when>
  <c:when test="${marks >= 40}">Grade: C</c:when>
  <c:otherwise>Grade: none</c:otherwise>
</c:choose>
curl "http://localhost:8080/student-portal/grade.jsp?marks=82"
curl "http://localhost:8080/student-portal/grade.jsp?marks=35"

Output:

Marks: 82
Result: Pass
Grade: B
Marks: 35
Result: Fail
Grade: none

How it works:

  • The request parameter is a string, but EL converts it to a number for >= and < comparisons.
  • c:choose stops at the first c:when whose test is true, so a score of 82 never reaches the C branch.
  • JSTL has no c:else; use c:choose whenever you need two or more branches.

Loop Over Collections With c:forEach

<c:forEach> repeats its body for every item of an array, List, Set or Map, or for a numeric range.

AttributeMeaning
itemsThe collection to loop over
varName of the current item
begin, end, stepRange or slice limits (0-based)
varStatusLoop info: index, count, first, last
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%
    request.setAttribute("modules", java.util.List.of("Basics", "OOP", "Collections", "Web"));
    request.setAttribute("fees", new java.util.TreeMap<>(java.util.Map.of("go", 2999, "java", 4999)));
%>
<c:forEach var="module" items="${modules}" varStatus="loop">
${loop.count}. ${module}${loop.first ? ' (start here)' : ''}${loop.last ? ' (final)' : ''}
</c:forEach>
Fees:
<c:forEach var="entry" items="${fees}">
- ${entry.key} = ${entry.value}
</c:forEach>
Even numbers: <c:forEach var="n" begin="2" end="10" step="2">${n} </c:forEach>
curl http://localhost:8080/student-portal/loop.jsp

Output:

1. Basics (start here)
2. OOP
3. Collections
4. Web (final)
Fees:
- go = 2999
- java = 4999
Even numbers: 2 4 6 8 10

How it works:

  • loop.count starts at 1 and loop.index at 0. first and last make it easy to style the first or final row.
  • Looping over a Map gives Map.Entry objects, so entry.key and entry.value read each pair. A TreeMap keeps the keys sorted.
  • With begin, end and step and no items, the tag counts numbers like a classic for loop.

<c:url> adds the context path to app-relative URLs. <c:param> adds query parameters and URL-encodes them for you.

<%@ page contentType="text/html;charset=UTF-8" session="false" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:url var="searchUrl" value="/courses">
  <c:param name="q" value="Java & Spring"/>
  <c:param name="page" value="2"/>
</c:url>
<a href="<c:url value='/course/java'/>">Java course</a>
<a href="${searchUrl}">Search results</a>
<a href="<c:url value='https://gocourse.in/blog'/>">Blog</a>
curl http://localhost:8080/student-portal/links.jsp

Output:

<a href="/student-portal/course/java">Java course</a>
<a href="/student-portal/courses?q=Java+%26+Spring&page=2">Search results</a>
<a href="https://gocourse.in/blog">Blog</a>

How it works:

  • URLs that start with / get the context path; absolute URLs are left untouched.
  • c:param encodes the space as + and & as %26. When stored with var, the & between parameters is escaped as &, which is correct inside an HTML attribute.
  • session="false" stops the page from creating a session. Otherwise c:url may append ;jsessionid=... on a visitor's first request.

Note: To keep session IDs out of URLs across the whole app, add <session-config><tracking-mode>COOKIE</tracking-mode></session-config> to web.xml.


Format Numbers, Currency and Dates With fmt Tags

The formatting library displays numbers and dates for a specific locale.

TagExamplePurpose
fmt:setLocale<fmt:setLocale value="en_IN"/>Locale for later fmt tags on the page
fmt:formatNumbertype="currency", type="percent", pattern="#,##0.0"Format numbers
fmt:formatDatepattern="dd MMM yyyy", timeZone="Asia/Kolkata"Format a java.util.Date
fmt:parseNumber<fmt:parseNumber value="${param.qty}" integerOnly="true"/>Text to number
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%
    java.time.ZonedDateTime batchStart = java.time.ZonedDateTime.of(2026, 12, 7, 18, 30, 0, 0,
            java.time.ZoneId.of("Asia/Kolkata"));
    request.setAttribute("startDate", java.util.Date.from(batchStart.toInstant()));
%>
<fmt:setLocale value="en_IN"/>
Fee: <fmt:formatNumber value="4999" type="currency"/>
Discount: <fmt:formatNumber value="0.125" type="percent" maxFractionDigits="1"/>
Rating: <fmt:formatNumber value="4.6666" maxFractionDigits="1"/>
Starts: <fmt:formatDate value="${startDate}" pattern="EEE, dd MMM yyyy 'at' hh:mm a" timeZone="Asia/Kolkata"/>
<fmt:setLocale value="en_US"/>
US fee: <fmt:formatNumber value="59" type="currency"/>
curl http://localhost:8080/student-portal/format.jsp

Output:

Fee: ₹4,999.00
Discount: 12.5%
Rating: 4.7
Starts: Mon, 07 Dec 2026 at 06:30 pm
US fee: $59.00

How it works:

  • The locale decides the currency symbol and separators: ₹ for en_IN, $ for en_US.
  • fmt:formatDate works with java.util.Date, so the java.time value is converted with Date.from(...). In real code, do that conversion in the servlet. See Java Date Formatting for the pattern letters.
  • timeZone makes the output independent of the server's own time zone.

String Functions With the fn Library

JSTL functions are used inside ${...} expressions.

FunctionExampleResult
fn:length${fn:length(modules)}Size of a collection or string
fn:toUpperCase${fn:toUpperCase('java')}JAVA
fn:containsIgnoreCase${fn:containsIgnoreCase(title, 'java')}true / false
fn:substring${fn:substring(text, 0, 20)}Part of a string
fn:split / fn:join${fn:join(fn:split(tags, ','), ' | ')}Split and rejoin
fn:escapeXml${fn:escapeXml(param.q)}HTML-escaped text
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<c:set var="title" value="  Java Programming: Beginner to Advanced  "/>
<c:set var="tags" value="java,oop,servlets,jsp"/>
Trimmed: [${fn:trim(title)}]
Length: ${fn:length(fn:trim(title))}
Short: ${fn:substring(fn:trim(title), 0, 16)}...
Mentions java? ${fn:containsIgnoreCase(title, 'JAVA')}
Tag count: ${fn:length(fn:split(tags, ','))}
Tags: ${fn:toUpperCase(fn:join(fn:split(tags, ','), ' | '))}
Safe: ${fn:escapeXml('<i>new</i>')}
curl http://localhost:8080/student-portal/functions.jsp

Output:

Trimmed: [Java Programming: Beginner to Advanced]
Length: 38
Short: Java Programming...
Mentions java? true
Tag count: 4
Tags: JAVA | OOP | SERVLETS | JSP
Safe: <i>new</i>

How it works:

  • Functions can be nested, like fn:length(fn:trim(title)), because each returns a normal value.
  • fn:split returns a String[], which fn:join and fn:length both accept.
  • fn:escapeXml is the function form of c:out escaping, handy inside attributes or longer expressions.

Real-World Example: JSTL in JSP for a Searchable Course List

This page lists courses with a search box and a level filter. The servlet filters the data, and the JSP uses JSTL for the table, the empty state, number formatting and safe links. No scriptlets appear in the view.

// CourseListServlet.java
package com.gocourse.portal;

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

@WebServlet("/courses")
public class CourseListServlet extends HttpServlet {

    public record CourseRow(String code, String title, String level, int feeInr, double rating) {}

    private static final List<CourseRow> ALL = List.of(
            new CourseRow("java", "Java Programming", "Beginner", 4999, 4.8),
            new CourseRow("spring", "Spring Boot with Java", "Advanced", 5999, 4.66),
            new CourseRow("python", "Python Programming", "Beginner", 3999, 4.7),
            new CourseRow("go", "Go Language", "Intermediate", 2999, 4.5));

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String query = request.getParameter("q") == null ? "" : request.getParameter("q").trim();
        String level = request.getParameter("level") == null ? "" : request.getParameter("level");

        List<CourseRow> results = ALL.stream()
                .filter(c -> c.title().toLowerCase().contains(query.toLowerCase()))
                .filter(c -> level.isEmpty() || c.level().equals(level))
                .toList();

        request.setAttribute("query", query);
        request.setAttribute("level", level);
        request.setAttribute("levels", List.of("Beginner", "Intermediate", "Advanced"));
        request.setAttribute("courses", results);
        request.getRequestDispatcher("/WEB-INF/views/courses.jsp").forward(request, response);
    }
}
<%-- /WEB-INF/views/courses.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" session="false" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<fmt:setLocale value="en_IN"/>
<form action="<c:url value='/courses'/>">
  <input name="q" value="${fn:escapeXml(query)}">
  <select name="level">
    <option value="">All levels</option>
    <c:forEach var="lvl" items="${levels}">
      <option ${lvl == level ? 'selected' : ''}>${lvl}</option>
    </c:forEach>
  </select>
</form>
<c:choose>
  <c:when test="${empty courses}">
    <p>No courses match "<c:out value='${query}'/>".</p>
  </c:when>
  <c:otherwise>
    <p>${fn:length(courses)} course${fn:length(courses) == 1 ? '' : 's'} found</p>
    <table>
      <c:forEach var="course" items="${courses}" varStatus="row">
        <tr class="${row.index % 2 == 0 ? 'even' : 'odd'}">
          <td>${row.count}</td>
          <td><a href="<c:url value='/course/${course.code}'/>"><c:out value="${course.title}"/></a></td>
          <td>${course.level}</td>
          <td><fmt:formatNumber value="${course.feeInr}" type="currency"/></td>
          <td><fmt:formatNumber value="${course.rating}" maxFractionDigits="1"/></td>
        </tr>
      </c:forEach>
    </table>
  </c:otherwise>
</c:choose>
curl -s "http://localhost:8080/student-portal/courses?q=java" | sed -n '/<p>/,$p'
curl -s "http://localhost:8080/student-portal/courses?q=%3Cb%3Erust" | grep "No courses"

Output:

<p>2 courses found</p>
    <table>
        <tr class="even">
          <td>1</td>
          <td><a href="/student-portal/course/java">Java Programming</a></td>
          <td>Beginner</td>
          <td>₹4,999.00</td>
          <td>4.8</td>
        </tr>
        <tr class="odd">
          <td>2</td>
          <td><a href="/student-portal/course/spring">Spring Boot with Java</a></td>
          <td>Advanced</td>
          <td>₹5,999.00</td>
          <td>4.7</td>
        </tr>
    </table>
    <p>No courses match "<b>rust".</p>

How it works:

  1. Logic stays in the servlet. Filtering by search text and level happens in Java with streams, so the JSP only displays the prepared courses list.
  2. Escaping everywhere user text appears. The search box value uses fn:escapeXml inside the attribute, and the empty-state message uses c:out, so the <b> in the second request is shown as text.
  3. Loop details. varStatus numbers the rows and alternates even/odd classes for striped tables. The selected attribute keeps the chosen level in the drop-down after searching.
  4. Locale-aware numbers. fmt:formatNumber shows Indian rupees and rounds the rating 4.66 to 4.7.
  5. Clean links. c:url adds the context path to every course link, and session="false" keeps session IDs out of them. The sed command only trims the form from the output. The same course data is exposed as JSON in REST API in Java.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about JSTL in JSP and get answers drawn from it.

Signed-in readers only.