Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 119 ยท Servlets and JSP

JSTL and Expression Language

Write JSP views without Java code using Expression Language and JSTL - scopes, c:if, c:forEach, c:out escaping, fmt formatting, servlet + JSP MVC and modern template engines.

The previous lesson ended with a rule: no Java code in JSP pages. That leaves two questions. How does a page read data without request.getAttribute(...)? And how does it loop or branch without a scriptlet for or if? The answers are Expression Language (EL), the ${...} syntax that reads values, and the Jakarta Standard Tag Library (JSTL), a set of tags such as <c:if> and <c:forEach> that handle control flow.

Together with a servlet that prepares the data, they give you a clean MVC structure: the servlet is the controller, a Java object is the model, and the JSP is a view that only displays. This lesson covers EL in depth (scopes, property access, operators, null handling), the JSTL core, formatting and function tags, the escaping rules that keep views safe, and how this design compares with modern template engines such as Thymeleaf. As before, JSP code is read-only here, and runnable programs reproduce what the container does.

Expression Language basics

An EL expression is written ${...} anywhere in template text or in a tag attribute. It is evaluated at request time and printed:

JSP
<h1>Hello, ${user.firstName}!</h1>
<p>You have ${cart.items.size()} items, total ${cart.total} EUR.</p>
<p>Searching for: ${param.q}</p>

EL is a small language of its own, not Java. It is designed for views: it reads values, is forgiving about null, and keeps logic short. (You may also see #{...}, the deferred syntax used by Jakarta Faces; in JSP you use ${...}.)

Where names come from: the four scopes

When EL sees a bare name such as user, it searches the four attribute scopes in order and takes the first match:

  1. page scope (pageContext.setAttribute)
  2. request scope (request.setAttribute), where controllers normally put the model
  3. session scope (session.setAttribute)
  4. application scope (servletContext.setAttribute)

If no scope has the name, the result is null, which prints as an empty string. To skip the search and name a scope explicitly, use the implicit maps pageScope, requestScope, sessionScope and applicationScope: ${sessionScope.user}. Being explicit avoids a subtle bug where a request attribute named user shadows the logged-in user in the session.

Other implicit objects

Object Contains Example
param first value of each request parameter ${param.q}
paramValues all values, as String[] ${paramValues.tag[1]}
header / headerValues request headers ${header['User-Agent']}
cookie Cookie objects by name ${cookie.theme.value}
initParam context init parameters from web.xml ${initParam.supportEmail}
pageContext the PageContext, and through it request, session, ... ${pageContext.request.contextPath}

${pageContext.request.contextPath} is the one you'll write most: it gives the app's context path (for example /shop) so links work wherever the app is deployed.

Property access and null handling

The dot and bracket operators read properties:

  • On a Map: ${prices.coffee} or ${prices['flat white']} looks up the key.
  • On a List or array: ${books[0]} reads by index.
  • On an ordinary object: ${user.firstName} calls getFirstName() (or isFirstName() for booleans).
  • On a record: Jakarta Expression Language 6.0 (Jakarta EE 11, Tomcat 11) reads record components directly, so ${book.title} calls title(). Older EL versions only understand getter names, so use classes with getters there, or call the method: ${book.title()}.

EL is null-safe for reading. If user is null, ${user.address.city} is simply empty instead of a NullPointerException. An index past the end of a list is also just null. But naming a property that doesn't exist on a non-null object, such as ${user.nmae}, throws PropertyNotFoundException, so typos still fail loudly.

The program below implements this resolution logic: the scope search, map keys, list indexes, getters and record components, and null safety. It's a simplified version of what the container's ELResolver chain does.

Java How EL resolves names and properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The bare title finds the request attribute because request scope is searched before session scope; sessionScope.title reaches past it. books[5].title and missing.anything both print nothing at all, while the misspelled user.nmae is an error. That combination, silent for missing data and loud for typos, is what makes EL comfortable in views.

Operators

EL has the usual operators, plus word forms that are handy inside XML attributes, where < and && are awkward:

Kind Operators
Arithmetic + - * / (div) % (mod)
Comparison == (eq) != (ne) < (lt) > (gt) <= (le) >= (ge)
Logical && (and) || (or) ! (not)
Empty test empty x: true for null, "", and empty collections, maps and arrays
Conditional cond ? a : b
String concatenation (EL 3.0+) +=: ${'Hello, ' += user.firstName}

Three behaviors differ from Java and trip people up:

  • + is always arithmetic. ${'1' + '2'} is 3, and ${'a' + 'b'} fails because a is not a number. Use += or just write the two expressions next to each other: ${first} ${last}.
  • / always divides as decimals. ${7 / 2} is 3.5, not 3.
  • null becomes 0 or false in arithmetic and logic: ${missing + 1} is 1.

EL 3.0 also added lambdas and stream-style operations, such as ${books.stream().filter(b -> b.price < 5).toList()}. They work, but filtering data is the controller's job. Keep views to reading and simple conditions.

JSTL: tags for logic

JSTL is a separate library: Tomcat implements JSP and EL but does not ship JSTL, so you add it to your project (the Jakarta API plus an implementation such as GlassFish's, both version 3.0 for jakarta.*). Then declare the libraries at the top of each page:

JSP
<%@ taglib prefix="c"   uri="jakarta.tags.core" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="fn"  uri="jakarta.tags.functions" %>

Old pages use URIs like http://java.sun.com/jsp/jstl/core with the javax version of JSTL; the tags themselves are the same.

The core tags

JSP
<%-- Print a value, escaped. default= is used when the value is null or empty --%>
<c:out value="${user.firstName}" default="guest"/>

<%-- Store a value in a scope (page by default) --%>
<c:set var="total" value="${cart.total}" scope="request"/>

<%-- One condition, no else --%>
<c:if test="${not empty errors}">
  <p class="error">Please fix the highlighted fields.</p>
</c:if>

<%-- if / else if / else --%>
<c:choose>
  <c:when test="${stock == 0}">Sold out</c:when>
  <c:when test="${stock lt 5}">Only ${stock} left</c:when>
  <c:otherwise>In stock</c:otherwise>
</c:choose>

<%-- Loop over a collection, array or map; varStatus gives position info --%>
<c:forEach items="${books}" var="book" varStatus="loop">
  <tr class="${loop.index % 2 == 0 ? 'even' : 'odd'}">
    <td>${loop.count}</td>
    <td><c:out value="${book.title}"/></td>
  </tr>
</c:forEach>

<%-- Numeric loop --%>
<c:forEach begin="1" end="${pageCount}" var="p"> ... </c:forEach>

<%-- Build a URL: adds the context path and URL-encodes parameters --%>
<c:url var="searchUrl" value="/search">
  <c:param name="q" value="${param.q}"/>
</c:url>
<a href="<c:out value='${searchUrl}'/>">Search again</a>

The loop status object has index (from 0), count (from 1), first, last, current, and begin, end and step for numeric loops. When items is a Map, each element is a Map.Entry with .key and .value. Less common tags are <c:remove> (delete an attribute), <c:forTokens> (split a string), <c:import> (include a URL's content), <c:redirect> and <c:catch>.

Here is the <c:forEach> table above rendered by a Java program that behaves like the tag, including the loop status and <c:out> escaping, so you can see the exact HTML a browser would receive.

Java What c:forEach and c:out produce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The & in "Pride & Prejudice" became &amp;, the <i> in the third title was printed as visible text instead of turning the cell italic, and the missing author fell back to the default value. The row classes alternate using loop.index, while the visible numbers use loop.count.

Escaping: ${...} alone is not safe

This is the single most important rule of JSP views: an EL expression in template text is not escaped. <p>${param.q}</p> is exactly as dangerous as the scriptlet <%= request.getParameter("q") %>. Use one of:

  • <c:out value="${param.q}"/>, which escapes by default (escapeXml="true");
  • ${fn:escapeXml(param.q)}, handy inside attributes: <input name="q" value="${fn:escapeXml(param.q)}">.

Escape every value that didn't come from your own code, including data from your database, which may have been typed by a user months ago. Only print raw HTML that you generated and sanitized yourself, and make that the visible exception in code review.

Formatting and functions

The fmt library formats numbers and dates for a locale, and also handles translated messages:

JSP
<fmt:setLocale value="de-DE"/>
<fmt:formatNumber value="${order.total}" type="currency" currencyCode="EUR"/>   <%-- 1.234,50 โ‚ฌ --%>
<fmt:formatNumber value="${rate}" type="percent" maxFractionDigits="1"/>
<fmt:formatDate value="${order.placedAt}" type="both" dateStyle="medium" timeStyle="short"/>

<fmt:setBundle basename="messages"/>
<fmt:message key="cart.empty"/>                                                  <%-- from messages_de.properties --%>

fmt:formatNumber uses Java's NumberFormat under the hood, so you can preview its output with plain Java, as the next program does. One limit to know: fmt:formatDate only accepts java.util.Date, not java.time types such as LocalDate. Format java.time values in the controller (or a small custom EL function) with DateTimeFormatter.

Java Locale-aware formatting behind fmt tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same amount appears with different decimal and grouping separators and with the โ‚ฌ sign before or after the number; the date order, month names and clock style change too. French groups digits with a narrow non-breaking space, which is correct typography and one more reason not to build these strings by hand. Also notice that 6.25% printed as 6.2%: NumberFormat rounds half-even by default (an exact 5 rounds toward the even neighbor), so set the rounding mode explicitly when the rule matters, for example for money.

The fn library adds string functions you call inside EL: fn:length (works on strings and collections, which .size() doesn't), fn:escapeXml, fn:contains, fn:startsWith, fn:toUpperCase, fn:trim, fn:replace, fn:substring, fn:split and fn:join.

JSP
<c:if test="${fn:length(books) gt 10}">Showing the first 10 of ${fn:length(books)} books.</c:if>

MVC with a servlet and a JSP view

Here is the whole pattern in one place. The servlet handles the request, talks to the service layer, puts the model into request attributes and forwards to a view under WEB-INF:

Java
@WebServlet("/books")
public class BookListServlet extends HttpServlet {

    private BookService books;

    @Override
    public void init() {
        books = (BookService) getServletContext().getAttribute("bookService");   // set by a listener
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String q = Objects.requireNonNullElse(request.getParameter("q"), "").strip();
        request.setAttribute("q", q);
        request.setAttribute("books", q.isEmpty() ? books.findAll() : books.search(q));
        request.getRequestDispatcher("/WEB-INF/views/books.jsp").forward(request, response);
    }
}
JSP
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ taglib prefix="fn" uri="jakarta.tags.functions" %>
<!DOCTYPE html>
<html lang="en">
<head><title>Books</title></head>
<body>
  <form action="${pageContext.request.contextPath}/books">
    <input name="q" value="${fn:escapeXml(q)}">
    <button>Search</button>
  </form>

  <c:choose>
    <c:when test="${empty books}">
      <p>No books match "<c:out value="${q}"/>".</p>
    </c:when>
    <c:otherwise>
      <ul>
        <c:forEach items="${books}" var="book">
          <li><c:out value="${book.title}"/> by <c:out value="${book.author}"/></li>
        </c:forEach>
      </ul>
    </c:otherwise>
  </c:choose>
</body>
</html>

The view contains no Java, can't be opened directly (it lives under WEB-INF), escapes everything it prints, and could be redesigned without touching the servlet. The servlet, in turn, can be tested without rendering HTML. This is the same split Spring MVC uses, with a DispatcherServlet in front (Spring MVC).

The runnable version below keeps the same structure on the JDK's HttpServer. The view is a template rendered by a 30-line engine in the style of Mustache: {{name}} prints an escaped value, {{#list}}...{{/list}} repeats a block for each element, and {{^list}}...{{/list}} renders only when the list is empty. Unlike JSP's ${...}, escaping is the default, and that is the main thing modern engines changed.

Java Servlet-style MVC with an escaping template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The controller never builds HTML, and the view never searches. The attack in the third query is printed harmlessly as text because the template engine escapes by default; with a JSP you get the same safety only if every value goes through <c:out> or fn:escapeXml.

Modern alternatives

JSP with JSTL still powers many applications, but new Java web projects usually choose a template engine that runs anywhere, not just inside a servlet container:

Engine Style Escapes by default Notes
JSP + JSTL tags and ${} in HTML no (<c:out> does) needs a servlet container; compiled to servlets
Thymeleaf attributes on real HTML: <td th:text="${book.title}"> yes the default for Spring MVC; templates open in a browser as static mock-ups
FreeMarker ${book.title}, <#list books as book> yes, with the HTML output format mature, used for emails and code generation too
Mustache / Handlebars {{title}}, {{#books}} yes "logic-less", same syntax in Java and JavaScript
JTE ${book.title()} with Java types yes compiled and type-checked: errors at build time

The ideas from this lesson carry over directly: the controller fills a model, the view only displays it, names are looked up in that model, and output is escaped unless you explicitly ask for raw HTML. Many teams also skip server-side templates entirely and serve JSON to a JavaScript front end; the REST API lessons show that side.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The request has an attribute title set to "A" and the session has title set to "B". What does ${title} print?

    EL searches page, request, session and application scope in that order and uses the first match. Use sessionScope.title to reach the session value.
  2. 2. The user attribute is null. What does ${user.address.city} print?

    EL is null-safe when reading. A null base gives a null result, and null prints as an empty string.
  3. 3. What is the value of ${7 / 2} in EL?

    The EL division operator always works with decimals, unlike integer division in Java.
  4. 4. Which line safely prints a search term from the URL?

    Plain EL and scriptlet expressions print raw text. c:out (or fn:escapeXml) escapes characters like < and quotes, so user input can't inject HTML.
  5. 5. In a servlet + JSP MVC design, which component should run the database query for a book list?

    The controller prepares the model and the view only displays it. That keeps the view simple and the logic testable.

Summary

  • EL (${...}) reads values in JSP. Bare names are searched in page, request, session and application scope; requestScope, sessionScope and friends name a scope directly.
  • Implicit objects include param, paramValues, header, cookie, initParam and pageContext (${pageContext.request.contextPath} for links).
  • Dot and bracket access works on maps, lists, getters and (with EL 6.0) records. Reading through null prints nothing; misspelled properties throw.
  • EL operators have word forms (eq, lt, and, empty); + is always numeric and / always decimal.
  • JSTL core tags provide logic: c:if, c:choose, c:forEach (with varStatus), c:set, c:url, c:out. Add JSTL to the project; Tomcat doesn't include it.
  • ${...} does not escape. Print outside data with <c:out> or fn:escapeXml.
  • fmt tags format numbers, dates and messages by locale (formatDate needs java.util.Date); fn functions handle strings and lengths.
  • Servlet as controller, request attributes as model, JSP under WEB-INF as view: the classic MVC that Spring MVC and modern template engines such as Thymeleaf build on.

Next: ORM and JPA Introduction moves from the web layer to the database and shows how objects are mapped to tables automatically.