The Java Web Development Series

What is JSP? Introduction to JavaServer Pages

One of the original Java web technologies, JavaServer Pages is still widely used to build dynamic web pages that connect to the Java backend

JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic, data-driven pages for your Java web applications. JSP is built on top of the Java Servlet specification. The two technologies typically work together, especially in older Java web applications. From a coding perspective, the most obvious difference between them is that with servlets you write Java code and then embed client-side markup (like HTML) into that code, whereas with JSP you start with the client-side script or markup, then embed JSP tags to connect your page to the Java backend.

JSP is also closely related to JSF (JavaServer Faces), a Java specification for building MVC (model-view-controller) web applications. JSP is a relatively simpler and older technology than JSF, which is the standard for Java web frameworks like Eclipse Mojarra, MyFaces, and PrimeFaces. While it is not uncommon to see JSP used as the frontend for older JSF applications, Facelets is the preferred view technology for modern JSF implementations.

While JSP may not be your first choice for building dynamic web pages, it is a core Java web technology. JSP pages are relatively quick and easy to build, and they interact seamlessly with Java servlets in a servlet container like Tomcat. You will encounter JSP in older Java web applications, and from time to time you may find it useful for building simple, dynamic Java web pages. As a Java developer, you should at least be familiar with JSP.

This article will be a quick introduction to JavaServer Pages, including the JSP Standard Tag Library (JSTL). Examples show you how to write a simple HTML page, embed JSP tags to connect to a Java servlet, and run the page in a servlet container.

See previous articles in this series to learn more about Java servlets and JavaServer Faces.

Writing JSP pages

A simple JSP page (.jsp) consists of HTML markup embedded with JSP tags. When the file is processed on the server, the HTML is rendered as the application view, a web page. The embedded JSP tags will be used to call server-side code and data. The diagram in Figure 1 shows the interaction between HTML, JSP, and the web application server.

jsp overview Matthew Tyson

Figure 1. JSP overview

Listing 1 shows a simple JSP page.

Listing 1. A simple JSP page


<html>
  <body>
    <p>${2 * 2} should equal 4</p>
  </body>
</html>

In Listing 1, you see a block of HTML that includes a JSP expression, which is an instruction to the Java server written using Expression Language (EL). In the expression "${2 * 2}", the "${}" is JSP syntax for interpolating code into HTML. When executed, the JSP will output the results of executing whatever is inside the expression. In this case, the output will be the number 4.

JSP in the servlet container

JSP pages must be deployed inside a Java servlet container. In order to deploy a Java web application based on JSP and servlets, you will package your .jsp files, Java code, and application metadata in a .war file, which is a simple .zip file with a conventional structure for web applications.

Once you've loaded the JSP into your servlet container, it will be compiled into a servlet. JSPs and Java servlets share similar characteristics, including the ability to access and respond to request objects. Apache Tomcat 9x is the reference implementation for the Servlet 4.0 and JSP 2.3 specifications. (Note that updates between JSP 2.2 and 2.3 are relatively minor.)

Example app for JSP

We'll use an example application in Tomcat to get you started with JavaServer Pages. If you don't already have Tomcat installed, browse over to the Tomcat download page and select the Tomcat installation for your operating system. As of this writing, Tomcat 9 is the current release, compatible with Servlet 4.0 and JSP 2.3.

You can install Tomcat as a Windows service, or run it from the command line with /bin/catalina.sh start or /bin/catalina.bat. Either way, start up Tomcat, then go to localhost:8080 to see the Tomcat welcome page shown in Figure 2.

tomcat welcome 1 Matthew Tyson

Figure 2. Tomcat welcome page

Implicit Objects in Tomcat

On the Tomcat welcome page, click the Examples link, then click JSP Examples.

Next, open the Implicit Objects Execute web application. Figure 3 shows output for this application. Take a minute to study this output.

implicit jsp Matthew Tyson

Figure 3. Sample JSP output

Request parameters

Implicit objects are built-in objects accessible via a JSP page. As a web page developer, you will use these objects to create access to things like request parameters, which are the data sent over from the browser when issuing an HTTP request. Consider the browser URL for Implicit Objects:


http://localhost:8080/examples/jsp/jsp2/el/implicit-objects.jsp?foo=bar

The param is ?foo=bar, and you can see it reflected in the output on the web page, where the table shows "EL Expression" and the value is "bar." To test this out, change the URL to http://localhost:8080/examples/jsp/jsp2/el/implicit-objects.jsp?foo=zork, hit Enter, and you'll see the change reflected in the output.

This example is a very simple introduction to using JSP tags to access server-side request parameters. In this case, the JSP page uses the built-in (implicit) object called param to access the web application's request parameters. The param object is available inside the JSP expression syntax that you saw in Listing 1.

In that example, we used an expression to do some math: ${2 * 2}, which output 4.

In this example, the expression is used to access an object and a field on that object: ${param.foo}.

JSP in a web application

On the Implicit Objects page, click the back arrow, followed by the Source link. This will lead you to the JSP code for the Implicit Objects web app, which is shown in Listing 2.

Listing 2. JSP code for the Implicit Objects web app


<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<html>
  <head>
    <title>JSP 2.0 Expression Language - Implicit Objects</title>
  </head>
  <body>
    <h1>JSP 2.0 Expression Language - Implicit Objects</h1>
    <hr>
    This example illustrates some of the implicit objects available
    in the Expression Language.  The following implicit objects are
    available (not all illustrated here):
    <ul>
      <li>pageContext - the PageContext object</li>
      <li>pageScope - a Map that maps page-scoped attribute names to
          their values</li>
      <li>requestScope - a Map that maps request-scoped attribute names
          to their values</li>
      <li>sessionScope - a Map that maps session-scoped attribute names
          to their values</li>
      <li>applicationScope - a Map that maps application-scoped attribute
          names to their values</li>
      <li>param - a Map that maps parameter names to a single String
          parameter value</li>
      <li>paramValues - a Map that maps parameter names to a String[] of
          all values for that parameter</li>
      <li>header - a Map that maps header names to a single String
          header value</li>
      <li>headerValues - a Map that maps header names to a String[] of
          all values for that header</li>
      <li>initParam - a Map that maps context initialization parameter
          names to their String parameter value</li>
      <li>cookie - a Map that maps cookie names to a single Cookie object.</li>
    </ul>

    <blockquote>
      <u><b>Change Parameter</b></u>
      <form action="implicit-objects.jsp" method="GET">
          foo = <input type="text" name="foo" value="${fn:escapeXml(param["foo"])}">
          <input type="submit">
      </form>
      <br>
      <code>
        <table border="1">
          <thead>
            <td><b>EL Expression</b></td>
            <td><b>Result</b></td>
          </thead>
          <tr>
            <td>\${param.foo}</td>
            <td>${fn:escapeXml(param["foo"])}&nbsp;</td>
          </tr>
          <tr>
            <td>\${param["foo"]}</td>
            <td>${fn:escapeXml(param["foo"])}&nbsp;</td>
          </tr>
          <tr>
            <td>\${header["host"]}</td>
            <td>${fn:escapeXml(header["host"])}&nbsp;</td>
          </tr>
          <tr>
            <td>\${header["accept"]}</td>
            <td>${fn:escapeXml(header["accept"])}&nbsp;</td>
          </tr>
          <tr>
            <td>\${header["user-agent"]}</td>
            <td>${fn:escapeXml(header["user-agent"])}&nbsp;</td>
          </tr>
        </table>
      </code>
    </blockquote>
  </body>
</html>

JSP functions

If you're familiar with HTML, then Listing 2 should look pretty familiar. You have the expected HTML <td> elements, followed by the ${ } JSP expression syntax introduced in Listing 1. But notice the value for param.foo: <td>${fn:escapeXml(param["foo"])}&nbsp;</td>. The "fn:escapeXML()" is a JSP function.

A JSP function encapsulates a chunk of reusable functionality. In this case, the functionality is to escape XML. JSP offers a variety of functions, and you can also create functions yourself. To use a function, you import its library into your JSP page, then call the function.

In Listing 2, the escapeXML function is included with the line:


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

The syntax is pretty clear: it imports the required functions and assigns them a prefix (in this case "fn") that can be used in all following expressions.

The JSP Standard Tag Library (JSTL)

The import line in Listing 2 calls taglib, which is short for tag library, or (in this case) JSP Standard Tag Library (JSTL). Tag libraries define reusable bits of functionality for JSP. JSTL is the standard tag library, containing a collection of taglibs that ship with every servlet and JSP implementation, including Tomcat.

The "functions" library is just one of the taglibs included with JSTL. Another common taglib is the core library, which you import by calling:


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

Like "fn", the "c" designation is conventional, and you will see it across most JSP pages.

Securing JSP pages

An example tag from the core library is


<c:out value = "${'<div>'}"/> 

which outputs the <div> tag with the XML already escaped. This function is important because outputting content directly to a web page via ${variable} opens the door to script injection attacks. This simple function is used to protect web pages from such attacks.

The core library also includes various tags for iteration and flow control (like IF/ELSE handling).

Calling taglibs in JSP pages

Now that you've got a handle on JSP basics, let's make a change to the example application. To start, locate the Implicit Object app in your Tomcat installation. The path is: apache-tomcat-8.5.33/webapps/examples/jsp/jsp2/el.

Open this file and locate the functions include:


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

just below this line, add a new line:


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

Hit Return and add another new line:


<c:out value = "${'This is a test of the JSTL Core Library'}"/>

Now reload the page at http://localhost:8080/examples/jsp/jsp2/el/implicit-objects.jsp?foo=bar.

You should see your updates reflected in the output.

1 2 Page 1
Page 1 of 2