JSTL in JSP
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:
| Library | Directive | Common prefix | Used for |
|---|---|---|---|
| Core | <%@ taglib prefix="c" uri="jakarta.tags.core" %> | c | Output, variables, conditions, loops, URLs |
| Formatting | <%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %> | fmt | Numbers, currency, dates, locales |
| Functions | <%@ taglib prefix="fn" uri="jakarta.tags.functions" %> | fn | String 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 usehttp://java.sun.com/jsp/jstl/corewith thejavaxversion, which does not work on Tomcat 10 and later. - The JAR sizes on your machine may differ slightly.
Print Values Safely With c:out
<c:out> prints a value and escapes HTML by default, which protects pages from script injection. Plain ${...} does not escape.
| Attribute | Meaning |
|---|---|
value | The expression to print |
default | Text shown when the value is null |
escapeXml | true (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:outconverts the special characters into entities, so the browser shows the comment exactly as typed.defaulthandles the missingnicknameparameter without anifblock.
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:setstores 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
courseNameshows. 499.90000000000003is normal floating-point rounding. Format money withfmt: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:choosestops at the firstc:whenwhose test is true, so a score of 82 never reaches theCbranch.- JSTL has no
c:else; usec:choosewhenever 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.
| Attribute | Meaning |
|---|---|
items | The collection to loop over |
var | Name of the current item |
begin, end, step | Range or slice limits (0-based) |
varStatus | Loop 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.countstarts at 1 andloop.indexat 0.firstandlastmake it easy to style the first or final row.- Looping over a
MapgivesMap.Entryobjects, soentry.keyandentry.valueread each pair. ATreeMapkeeps the keys sorted. - With
begin,endandstepand noitems, the tag counts numbers like a classicforloop.
Build Links With c:url and c:param
<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:paramencodes the space as+and&as%26. When stored withvar, the&between parameters is escaped as&, which is correct inside an HTML attribute.session="false"stops the page from creating a session. Otherwisec:urlmay 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>toweb.xml.
Format Numbers, Currency and Dates With fmt Tags
The formatting library displays numbers and dates for a specific locale.
| Tag | Example | Purpose |
|---|---|---|
fmt:setLocale | <fmt:setLocale value="en_IN"/> | Locale for later fmt tags on the page |
fmt:formatNumber | type="currency", type="percent", pattern="#,##0.0" | Format numbers |
fmt:formatDate | pattern="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:
₹foren_IN,$foren_US. fmt:formatDateworks withjava.util.Date, so thejava.timevalue is converted withDate.from(...). In real code, do that conversion in the servlet. See Java Date Formatting for the pattern letters.timeZonemakes the output independent of the server's own time zone.
String Functions With the fn Library
JSTL functions are used inside ${...} expressions.
| Function | Example | Result |
|---|---|---|
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:splitreturns aString[], whichfn:joinandfn:lengthboth accept.fn:escapeXmlis the function form ofc:outescaping, 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:
- Logic stays in the servlet. Filtering by search text and level happens in Java with streams, so the JSP only displays the prepared
courseslist. - Escaping everywhere user text appears. The search box value uses
fn:escapeXmlinside the attribute, and the empty-state message usesc:out, so the<b>in the second request is shown as text. - Loop details.
varStatusnumbers the rows and alternateseven/oddclasses for striped tables. Theselectedattribute keeps the chosen level in the drop-down after searching. - Locale-aware numbers.
fmt:formatNumbershows Indian rupees and rounds the rating 4.66 to 4.7. - Clean links.
c:urladds the context path to every course link, andsession="false"keeps session IDs out of them. Thesedcommand only trims the form from the output. The same course data is exposed as JSON in REST API in Java.