Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 119 ยท Servlets and JSP

JavaServer Pages (JSP)

Learn JavaServer Pages - directives, scriptlets and why to avoid them, implicit objects, includes, and how a JSP is translated and compiled into a servlet.

Writing HTML from a servlet with out.println("<tr><td>" + name + "</td></tr>") gets painful after the third table. JavaServer Pages (JSP, now officially Jakarta Pages) turn that around: you write an HTML file and mark the dynamic parts with special tags. The container converts the page into a servlet the first time it is requested, so a JSP is really just a servlet written inside out.

JSP has been part of Java web development since 1999. You will meet it in many existing enterprise applications, in interview questions and in older tutorials, so you need to read it confidently. You also need to know which parts of it are considered harmful today. This lesson covers the syntax (directives, scripting elements, actions), the implicit objects, and, with runnable programs, exactly how a JSP becomes a compiled Java class. The next lesson replaces the risky parts with the modern style, JSTL and Expression Language.

A first JSP

A JSP is a text file, usually HTML, with the extension .jsp. Here is a complete page in the old style, using every kind of JSP element. Read it once now; the sections below take it apart.

JSP
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.time.LocalDate, java.util.List" %>
<%-- A JSP comment: removed during translation, never sent to the browser --%>
<%! private static final String SHOP = "Northwind Books"; %>
<!DOCTYPE html>
<html lang="en">
<head><title><%= SHOP %></title></head>
<body>
  <h1>Welcome to <%= SHOP %></h1>
  <p>Today is <%= LocalDate.now() %>.</p>
  <%
    List<String> books = (List<String>) request.getAttribute("books");
    if (books == null || books.isEmpty()) {
  %>
    <p>No books found.</p>
  <% } else { %>
    <ul>
    <% for (String title : books) { %>
      <li><%= title %></li>
    <% } %>
    </ul>
  <% } %>
  <!-- An HTML comment: sent to the browser as-is -->
</body>
</html>

Everything that is not inside <% ... %> is template text, copied to the response unchanged. The rest falls into three groups.

Directives: instructions for the translator

Directives start with <%@ and affect how the page is translated, not what it outputs at run time.

Directive Example Purpose
page <%@ page contentType="text/html; charset=UTF-8" %> settings for this page (see below)
include <%@ include file="/WEB-INF/fragments/header.jspf" %> copy another file's source in at translation time
taglib <%@ taglib prefix="c" uri="jakarta.tags.core" %> make a tag library available under a prefix

Useful page attributes:

  • contentType and pageEncoding: the response type and the encoding of the .jsp file itself. Always set both to UTF-8.
  • import: a comma-separated list of classes or packages for scripting code.
  • session="false": don't create or expose a session for this page. A good default for public pages, because by default every JSP creates a session.
  • errorPage="/WEB-INF/views/error.jsp" and isErrorPage="true": forward to an error page when the page throws; only an error page gets the exception object.
  • trimDirectiveWhitespaces="true": drop the blank lines that directives and scriptlets otherwise leave in the HTML.
  • isELIgnored: switch off Expression Language (it is on by default).

Scripting elements: Java inside HTML

Element Syntax Becomes in the generated servlet
Expression <%= expr %> out.print(expr); inside the request method
Scriptlet <% statements %> the statements, copied into the request method
Declaration <%! member %> a field or method of the generated class
JSP comment <%-- text --%> nothing at all

Expressions have no semicolon, because they are wrapped in a call. Scriptlets are raw Java, so braces can open in one scriptlet and close in another, with HTML in between, as the for loop above does. That is legal, and it is also why scriptlet-heavy pages become unreadable so quickly.

Why scriptlets are discouraged

The JSP specification itself has recommended against scriptlets for years. In code review, a new scriptlet is a red flag. The reasons are practical:

  • No escaping. <%= request.getParameter("q") %> prints user input raw, which is a cross-site scripting (XSS) hole. You'll see this happen below.
  • Logic in the view. Database calls and business rules end up in HTML files, where they can't be unit-tested or reused.
  • Thread-safety traps. A declaration like <%! int visits; %> becomes a field of a servlet instance shared by every request (see Servlet Lifecycle and Deployment).
  • Late errors. A typo in a scriptlet is a compile error that appears only when someone requests the page, possibly in production.
  • Tooling. Mixed Java and HTML confuses formatters, linters and designers.

The modern rule: the servlet (or controller) does the work and puts results into request attributes; the JSP only displays them with EL and JSTL. You can even forbid scripting for all pages in web.xml:

XML
<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

How a JSP becomes a servlet

The container maps *.jsp to a special servlet, the JSP engine (in Tomcat it's called Jasper). On the first request for a page, it:

  1. Translates index.jsp into Java source: a class such as index_jsp that extends a base servlet class. Template text becomes out.write("...") calls, expressions become out.print(...), scriptlets are pasted into the request method _jspService, and declarations become class members.
  2. Compiles that source into a .class file.
  3. Loads the class, creates one instance, calls jspInit() and then _jspService(request, response) for this and every later request.

In Tomcat you can find the generated files under work/Catalina/localhost/<app>/org/apache/jsp/, which is very helpful when a stack trace points at index_jsp.java line 87. In development mode the engine checks the .jsp file's timestamp and repeats the translation when it changes; in production you can precompile all pages during the build (Jasper's JspC tool, available as Maven and Gradle plugins) to avoid the slow first request and catch errors early.

The program below is a small JSP translator. It handles directives with import, comments, declarations, expressions, scriptlets and template text, and prints the Java class it generates, structured like Jasper's output but far simpler.

Java Translating a JSP into Java source

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.

Read the generated class from top to bottom. The import attribute became an import statement. The declaration visits became a field, which is why it is shared by all requests. The comment vanished. Every other element landed, in order, inside _jspService: template text as out.write, expressions as out.print, and scriptlets pasted in verbatim, including the half-open for loop whose closing brace comes from a later scriptlet. Even the newlines after directives turned into out.write("\n") calls, which is where the blank lines in JSP output come from.

Watching the full cycle

Translation is only half the story. The next program goes all the way: it translates a page, compiles the generated source with the JDK's built-in compiler (javax.tools.JavaCompiler, the same tool Jasper can use), loads the class and runs it for several requests. Halfway through, the page "file" is edited, so the container notices the new timestamp and recompiles, just like Tomcat in development mode.

Java Translate, compile and run a JSP

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.

Only the first request and the first request after the edit pay for translation and compilation; the others just call the already loaded class. Look at the visitor numbers, too: the edit produced a new class with a new instance, so the visits field started from zero again. A counter kept in a JSP declaration is not only unsafe under concurrent requests but also silently reset by every recompile and every server restart. Real counters belong in a database.

Implicit objects

Inside scriptlets and expressions, a JSP can use several variables without declaring them. The generated _jspService method creates them before your code runs:

Object Type What it is
request HttpServletRequest the current request
response HttpServletResponse the current response
out JspWriter a buffered writer for the response body
session HttpSession the user's session (absent with session="false")
application ServletContext the web application, shared by all users
config ServletConfig this page's servlet configuration
pageContext PageContext access to all of the above, plus page-scope attributes
page Object the page instance itself (this); almost never used
exception Throwable the error, only in pages with isErrorPage="true"

pageContext is the most interesting one. Besides holding page-scope attributes, its findAttribute(name) method searches the page, request, session and application scopes in that order. That search is exactly what Expression Language does when you write ${user}, as you'll see in the next lesson.

The output buffer matters for forwards and redirects. By default, out buffers 8 KB. As long as nothing has been flushed, a page can still forward, redirect or set headers. Once the buffer fills and is sent, the response is committed and a later <jsp:forward> throws IllegalStateException.

Standard actions and includes

Actions are XML-style tags with the jsp: prefix that run at request time:

JSP
<jsp:include page="/WEB-INF/fragments/cart-summary.jsp">
    <jsp:param name="compact" value="true"/>
</jsp:include>

<jsp:forward page="/WEB-INF/views/login.jsp"/>

There are two ways to include another file, and the difference is a favorite interview question:

<%@ include file="..." %> <jsp:include page="..."/>
When translation time request time
How the file's source is pasted in; one servlet is generated the other page runs as its own servlet and its output is inserted
Variables shared with the including page not shared; pass data with <jsp:param> or attributes
After editing the included file the including page may need retranslating the change shows up on the next request
Typical use static fragments: header markup, common taglib declarations (.jspf) dynamic fragments that do their own work

The old <jsp:useBean>, <jsp:setProperty> and <jsp:getProperty> actions created and read JavaBeans from scopes. They are largely obsolete; EL does the same thing in far less code (the section on custom tags and beans below shows when they still appear).

Here is the complete set of standard actions, so you can read any older JSP:

Action What it does
<jsp:include page="..."> runs another page at request time and inserts its output
<jsp:forward page="..."> hands the request to another page; the browser's URL does not change and nothing after the tag runs
<jsp:param name="..." value="..."/> adds a request parameter; nested inside include, forward or plugin
<jsp:useBean id="user" class="shop.User" scope="session"/> finds the bean named user in the scope, or creates it
<jsp:setProperty name="user" property="*"/> copies request parameters into the bean's setters (property="*" matches all by name)
<jsp:getProperty name="user" property="name"/> writes the property's value to the page (no escaping)
<jsp:plugin type="applet" code="..."> embedded a Java applet or JavaBean in the browser; obsolete because browsers no longer run applets
<jsp:element>, <jsp:attribute>, <jsp:body> build an XML element dynamically; <jsp:attribute> supplies an attribute whose value is itself JSP content, and <jsp:body> supplies the element's body (also used inside tag files to pass fragments)
<jsp:text> writes literal template text; useful in XML-syntax JSP documents
<jsp:directive.page> / <jsp:root> the XML spelling of directives, used by JSP documents (.jspx)

Two short examples: jsp:element with jsp:attribute builds a tag whose attribute values are computed, and jsp:forward carries an extra parameter to the target page:

JSP
<jsp:element name="meta">
  <jsp:attribute name="name">generator</jsp:attribute>
  <jsp:attribute name="content">${initParam.appName} ${initParam.appVersion}</jsp:attribute>
</jsp:element>

<jsp:forward page="/WEB-INF/views/login.jsp">
  <jsp:param name="next" value="${pageContext.request.requestURI}"/>
</jsp:forward>

The parameters added by jsp:param appear next to the original request parameters; when a name is repeated, the new value comes first, so request.getParameter("next") returns it.

Escaping: the bug every scriptlet page has

<%= value %> prints the value exactly as it is. If the value came from a user, the user is now writing your HTML. The next program renders a search-results heading for several inputs, once the scriptlet way and once with the escaping that JSTL's <c:out> and fn:escapeXml perform.

Java Raw expressions vs escaped output

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 first input is harmless either way. The second shows that even innocent text needs escaping: a bare & is invalid HTML. The third is a stored or reflected XSS attack that would send the visitor's cookies to another site (unless they are HttpOnly; see Sessions and Cookies). The fourth breaks out of the attribute's quotes and adds an event handler. After escaping, all four are just text. HTML escaping protects element content and quoted attributes; values placed inside <script> blocks, URLs or CSS need their own encoding, which is another reason to keep data out of scripts and pass it through data- attributes instead.

Custom tags, tag files and JavaBeans

JSTL gives you standard tags, but sooner or later you repeat a block of markup, a card, an alert box or a formatted price, in dozens of pages. A custom tag lets you name that block once and use it like <ui:alert type="warning">Saved</ui:alert>. There are two ways to write one: a tag file (almost no Java) and a tag handler class (full control).

Tag files: the easy way

A tag file is a JSP fragment saved with the .tag extension under /WEB-INF/tags/. It declares its inputs with the attribute directive and renders the tag's body with <jsp:doBody/>:

JSP
<%-- /WEB-INF/tags/alert.tag --%>
<%@ tag description="A styled message box" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<%@ attribute name="type" required="false" type="java.lang.String" %>

<div class="alert alert-<c:out value="${empty type ? 'info' : type}"/>" role="alert">
  <jsp:doBody/>
</div>

A page uses it by pointing a prefix at the folder, with no descriptor file at all:

JSP
<%@ taglib prefix="ui" tagdir="/WEB-INF/tags" %>

<ui:alert type="warning">Your session expires in 5 minutes.</ui:alert>
<ui:alert>Profile saved.</ui:alert>

The file name becomes the tag name (alert.tag is <ui:alert>). Tag files are the right choice for layout pieces and repeated markup, because designers can edit them like any JSP.

Tag handlers: SimpleTagSupport and a TLD

When the tag needs real Java (formatting, a call to a utility, conditional body output), extend SimpleTagSupport. Each attribute is a setter, and doTag() runs when the tag executes:

Java
public class PriceTag extends SimpleTagSupport {

    private BigDecimal amount;
    private String currency = "USD";

    public void setAmount(BigDecimal amount) { this.amount = amount; }
    public void setCurrency(String currency) { this.currency = currency; }

    @Override
    public void doTag() throws JspException, IOException {
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
        format.setCurrency(Currency.getInstance(currency));
        String text = amount == null ? "n/a" : format.format(amount);
        getJspContext().getOut().write(text);              // write to the page output
        // To render the tag's body: getJspBody().invoke(null);
    }
}

A tag library descriptor (TLD) file registers the tag. Put it in /WEB-INF/ (or META-INF/ inside a JAR) with a .tld extension:

XML
<taglib xmlns="https://jakarta.ee/xml/ns/jakartaee" version="4.0">
  <tlib-version>1.0</tlib-version>
  <short-name>shop</short-name>
  <uri>https://example.com/tags/shop</uri>

  <tag>
    <name>price</name>
    <tag-class>com.example.web.PriceTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
      <name>amount</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.math.BigDecimal</type>
    </attribute>
    <attribute>
      <name>currency</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>
JSP
<%@ taglib prefix="shop" uri="https://example.com/tags/shop" %>
Total: <shop:price amount="${order.total}" currency="EUR"/>

rtexprvalue set to true means the attribute may hold an EL expression such as ${order.total}. Remember to escape user-supplied text a tag writes, exactly as you would with <c:out>.

The model below runs the same life cycle in plain Java without a container: set the attributes through setters, call doTag(), and give the tag access to its body and output. Try the missing-attribute and escaping cases.

Java A model of the SimpleTag life cycle: attributes, body and output

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 attribute named type was escaped, so the attempted injection stayed inside the class attribute. The body text is not escaped, because it is page markup that the author wrote. Escaping the attribute values a tag receives is the handler's job.

JavaBeans in a page: useBean, setProperty and getProperty

A JavaBean is a plain class with a public no-argument constructor and getters and setters. Three standard actions work with beans stored in a scope (page, request, session or application):

JSP
<jsp:useBean id="filter" class="com.example.web.SearchFilter" scope="request"/>
<jsp:setProperty name="filter" property="*"/>           <%-- copy matching request parameters into the bean --%>

Searching for: <jsp:getProperty name="filter" property="query"/>

useBean looks for an attribute named filter in the chosen scope and creates the bean if it is missing. <jsp:setProperty property="*"/> copies request parameters whose names match bean properties, converting simple types automatically, which is handy for forms but dangerous: an attacker can send any parameter that matches a property name. Use it only on beans that hold nothing sensitive, or set properties one by one. In modern pages, prefer a servlet that builds the bean and an EL expression ${filter.query} to read it, as in JSTL and Expression Language.

Exception pages

An error inside a JSP can show the visitor a raw stack trace. Handle it in one of two ways. A page can name its own handler with errorPage, and the handler declares itself with isErrorPage:

JSP
<%-- any page --%>
<%@ page errorPage="/WEB-INF/views/error.jsp" %>

<%-- /WEB-INF/views/error.jsp --%>
<%@ page isErrorPage="true" %>
<% response.setStatus(500); %>
<h1>Something went wrong</h1>
<p>Reference: <c:out value="${requestScope['jakarta.servlet.error.request_uri']}"/></p>

Application-wide handling is better done in web.xml, where one entry covers every servlet and JSP and can match status codes or exception types:

XML
<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/views/not-found.jsp</location>
</error-page>
<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/WEB-INF/views/error.jsp</location>
</error-page>

On an error page, the container provides request attributes such as jakarta.servlet.error.status_code, jakarta.servlet.error.exception and jakarta.servlet.error.request_uri. Log the exception on the server and show visitors only a friendly message and a reference number, never the stack trace, because stack traces reveal class names, paths and library versions to attackers.

JSP today

JSP still works and is maintained as part of Jakarta EE (Jakarta Pages 4.0 ships with Jakarta EE 11, and Tomcat 11 supports it). Existing applications with thousands of JSPs run happily on it. For new projects, though, most teams choose a template engine that doesn't compile to servlets and works outside a servlet container: Thymeleaf (the default choice with Spring MVC), FreeMarker, Mustache, Pebble or JTE. Spring Boot even documents limitations for JSP when packaged as an executable JAR. The next lesson shows the JSP style worth knowing, with no scriptlets at all, and compares it with those alternatives.

If you maintain JSP code, a few rules keep it healthy:

  • Put JSPs under WEB-INF so they can only be reached through a servlet.
  • Set contentType and pageEncoding to UTF-8, and session="false" where no session is needed.
  • No scriptlets, no declarations. Use EL and JSTL, and escape every value with <c:out>.
  • Precompile pages in the build to catch errors before deployment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the generated servlet, where does the code from <%! int count = 0; %> end up?

    Declarations become class members. Because the container uses one instance for all requests, the field is shared and not thread-safe.
  2. 2. What does the browser receive for <%-- secret note --%> and for <!-- secret note -->?

    JSP comments disappear when the page is translated. HTML comments are template text, so they are sent to the browser where anyone can read them with View Source.
  3. 3. Why is the first request to a JSP slower than the following ones?

    The JSP engine translates and compiles the page on first use (unless it was precompiled). Later requests reuse the loaded class.
  4. 4. Which include runs the included page as a separate servlet at request time?

    jsp:include dispatches to the other page while handling the request and inserts its output. The include directive copies source text at translation time.
  5. 5. A page contains <%= request.getParameter("q") %>. What is the main risk?

    Expressions print values raw. Anything the user sends, including script tags or attribute-breaking quotes, becomes part of your HTML. Use c:out or fn:escapeXml.

Summary

  • A JSP is an HTML template with dynamic parts; the container translates it into a servlet class, compiles it and runs _jspService for each request.
  • Directives (<%@ page %>, <%@ include %>, <%@ taglib %>) configure translation. Set UTF-8 for contentType and pageEncoding.
  • Scripting elements: expressions <%= %> print, scriptlets <% %> run statements, declarations <%! %> add class members. Avoid all three in new code: they print unescaped, mix logic into views and create shared fields.
  • Implicit objects such as request, session, application, out and pageContext are created for you; pageContext.findAttribute searches page, request, session and application scope.
  • <%@ include %> pastes source at translation time; <jsp:include> runs another page at request time.
  • Escape every value that came from outside, keep JSPs under WEB-INF, and precompile them in the build. New projects usually pick a template engine such as Thymeleaf instead.

Next: JSTL and Expression Language shows how to write JSP views with no Java code at all.