Table of Contents

1. Overview

JavaServer Pages (JSP) allows dynamic content injection into static contents using Java and Java Servlets. We can make requests to a Java Servlet, perform relevant logic, and render a specific view server-side to be consumed client-side. This article will provide a thorough overview of JavaServer Pages using Java 8 and Jave 7 EE.

We’ll start by exploring a few key concepts relevant to JSP: namely, the difference between dynamic and static contents, the JSP lifecycle, and JSP syntax as well as directives and the implicit objects created at compilation!

2. JavaServer Pages

JavaServer Pages (JSP) enabled Java-specific data to be passed into or placed within a .jsp view and consumed client-side.

JSP files are essentially .html files with some extra syntax, and a couple of minor initial differences:

  1. the .html suffix is replaced with .jsp (it’s considered a .jsp filetype) and
  2. the following tag is added to the top of the .html markup elements:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Let’s go over some of the key concepts in JSP.

2.1. JSP Syntax

There are two ways to add Java code to a .jsp. First, we can use basic Java Scriptlet syntax which involves placing Java code blocks within two Scriptlet tags:

<% Java code here %>

The second method is specific to XML:

<jsp:scriptlet>
    Java code here
</jsp:scriptlet>

Importantly, one can use conditional logic clientside with JSP by using if, then, and else clauses and then wrapping the relevant blocks of markup with those brackets.

<% if (doodad) {%>
    <div>Doodad!</div>
<% } else { %>
    <p>Hello!</p>
<% } %>

For example, if doodad is true, we would display the first, div element otherwise we would display the second, p element!

2.2. Static and Dynamic Contents

Static web contents are fixed assets that are consumed independently of RESTful, SOAP, HTTP, HTTPS requests, or other user-submitted information.

Static content, however, is fixed and is not modified by user inputs. Dynamic web contents are those assets that respond to, are modified by, or change in light of user actions or information!

JSP technology allows for the clean separation of responsibilities between dynamic and static contents.

The server (servlet) manages the dynamic contents and the client (the actual .jsp page) is the static context into which dynamic contents are injected.

Let’s take a look at the implicit objects that are created by JSP and which allow you to access JSP-relevant data server-side!

2.3. Implicit Objects

Implicit objects are generated by the JSP engine automatically during compilation.

Implicit objects include the HttpRequest and HttpResponse objects and expose various serverside functionalities for use in your servlet and for interacting with your .jsp! Here’s the list of implicit objects that are created:

request
request belongs to the class javax.servlet.http.HttpServletRequest. The request object exposes all user inputs data and makes it available serverside.

response
response belongs to the class javax.servlet.http.HttpServletResponse and determines what is passed back clientside after a request is made.

Let’s take a closer look at the request and response implicit objects since they’re the most important and heavily-used ones.

The example below demonstrates a very simple, incomplete, servlet method to handle GET requests. I’ve omitted most of the details so that we can focus on how to use the request and response objects:

protected void doGet(HttpServletRequest request, 
  HttpServletResponse response) throws ServletException, IOException {
    String message = request.getParameter("message");
    response.setContentType("text/html");
    . . .
}

First, we see that the request and response objects are passed in as parameters into the method making them available within its scope.

We can access request parameters using the .getParameter() function. Above, we snag the message parameter and initialize a string variable so we can use it in our server-side logic. We can also access the response object which determines what and how the data passed into the view will be.

Above we set the content type on it. We don’t need to return the response object to have it’s payload display on the JSP page at render!

out
out belongs to the class javax.servlet.jsp.JspWriter and is used to write content to the client.

There are at least two ways to print to your JSP page and its worth discussing both here. out is created automatically and allows you to write to memory and then to the response object:

out.print(“hello”);
out.println(“world”);

That’s it!

The second approach can be more performant since it allows you to write directly to the response object! Here, we use PrintWriter:

PrintWriter out = response.getWriter();
out.println("Hello World");

2.4. Other Implicit Objects

Here are some other Implicit objects that are also good to know!

session
session belongs to the class javax.servlet.http.HttpSession maintains user data for the duration of the session.

application
application belongs to the class javax.servlet.ServletContext stores application-wide parameters set at initialization or that need to be accessed application-wide.

exception
exception belongs to the class javax.servlet.jsp.JspException is used to display error messages on JSP pages which have the tag <%@ page isErrorPage=”true” %>.

page
page belongs to the class java.lang.Object allows one to access or reference current servlet information.

pageContext
pageContext belongs to the class javax.servlet.jsp.PageContext defaults to page scope but can be used for accessing request, application, and session attributes.

config
config belongs to the class javax.servlet.ServletConfig is the servlet configuration object allowing one to get the servlet context, name, and configuration parameters.

Now that we’ve covered the implicit objects provided by JSP, let’s turn to directives which allow .jsp pages to (indirectly) access some of these objects.

2.5. Directives

JSP supplies out of the box directives that can be used to specify core functionalities for our JSP files. There are two parts to JSP directives: (1) the directive itself and (2) the attribute of that directive which is assigned a value.

The three kinds of directives that can be referenced using directive tags are <%@ page … %> which defines dependencies and attributes of the JSP including content type and language, <%@ include … %> which specifies an import or file to be used, and <%@ taglib …%> which specifies a tag library defining custom actions to be used by a page.

So, as an example, a page directive would be specified using JSP tags in the following way: <%@ page attribute=”value” %>

And, we can do that using XML as follows: <jsp:directive.page attribute=”value” />

2.6. Page Directive Attributes

There are a lot of attributes that can be declared within a page directive:

autoFlush <%@ page autoFlush=”false” %>

autoFlush controls the buffer output, clearing it out when the buffer size is reached. The default value is true.

buffer <%@ page buffer=”19kb” %>

buffer sets the size of the buffer used by our JSP page. The default value is 8kb.

errorPage <%@ page errorPage=”errHandler.jsp” %>

errorPage specifies a JSP page as an error page.

extends <%@ page extends=”org.apache.jasper.runtime.HttpJspBase” %>

extends specifies the super class of the corresponding servlet code.

info <%@ page info=”This is my JSP!” %>

info is used to set a text-based description for the JSP.

isELIgnored <%@ page isELIgnored=”true” %>

isELIgnored states whether or not the page will ignore Expression Language (EL) in JSP. EL enables the presentation layer to communicate with Java managed beans and does so using ${…} syntax and while we won’t get into the nitty-gritties of EL here, there are several examples found below that are sufficient to build our example JSP app! The default value for isELIgnored is false.

isErrorPage <%@ page isErrorPage=”true” %>

isErrorPage says whether or not a page is an error page. We must specify an error page if we create an error handler for our page within the application.

isThreadSafe <%@ page isThreadSafe=”false” %>

isThreadSafe has a default value of true. isThreadSafe determines whether or not the JSP can use Servlet multi-threading. In general, you would never want
to turn off that functionality.

language <%@ page language=”java” %>

language determines what scripting language to use in the JSP. The default value is Java.

session <%@ page session=”value”%>

session determines whether or not to maintain the HTTP session. It defaults to true and accepts values of true or false.

trimDirectiveWhitespaces <%@ page trimDirectiveWhitespaces =”true” %>

trimDirectiveWhitespaces stripes out white-spaces in the JSP page condensing the code into a more compact block at compile-time. Setting this value to true may help to reduce the size of the JSP code. The default value is false.

3. Three Examples

Now that we’ve reviewed the concepts central to JSP, let’s apply those concepts to some basic examples that will help you to get your first JSP-serving servlet up and running!

There are three main ways to inject Java into a .jsp and we’ll explore each of those ways below using native functionalities in Java 8 and Jakarta EE.

First, we’ll render our markup server-side to be displayed client-side. Second, we’ll look at how to add Java code directly into our .jsp file independent of javax.servlet.http‘s request and response objects.

Third, we’ll demonstrate how to both forward an HttpServletRequest to a specific .jsp and bind server-side processed Java to it.

Let’s set up our project in Eclipse using the File/New/Project/Web/Dynamic web project/ type to be hosted in Tomcat! You should see after creating the project:

|-project
  |- WebContent
    |- META-INF
      |- MANIFEST.MF
    |- WEB-INF
      |- lib
      |- src

We’re going to add a few files to the application structure so that we end up with:

|-project
  |- WebContent
    |- META-INF
      |- MANIFEST.MF
    |- WEB-INF
      |-lib
      *-web.xml
        |- ExampleTree.jsp
        |- ExampleTwo.jsp
        *- index.jsp
      |- src
        |- com
          |- baeldung
            *- ExampleOne.java
            *- ExampleThree.java

Let’s set up index.jsp which will be displayed when we access the URL context in Tomcat 8:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>JSP Examples</title>
    </head>
    <body>
        <h1>Simple JSP Examples</h1>
        <p>Invoke HTML rendered by Servlet: <a href="ExampleOne" target="_blank">here</a></p>
        <p>Java in static page: <a href="ExampleTwo.jsp" target="_blank">here</a></p>
        <p>Java injected by Servlet: <a href="ExampleThree?message=hello!" target="_blank">here</a></p>
    </body>
</html>

There are three a, each linking to one of the examples we’ll go through below in sections 4.1 through 4.4.

We also need to make sure that we’ve got our web.xml set up:

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <servlet-name>ExampleOne</servlet-name>
    <servlet-class>com.baeldung.ExampleOne</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ExampleOne</servlet-name>
    <url-pattern>/ExampleOne</url-pattern>
</servlet-mapping>

A main note here is – how to correctly map each of our servlets to a particular servlet-mapping.Doing so associates each servlet with a specific endpoint where it can consumed! Now, we’ll go through each of the other files below!

3.1. HTML Rendered in Servlet

In this example, we’ll actually skip building a .jsp file!

Instead, we’ll create a string representation of our markup and then write it to the GET response with PrintWriter after ExampleOne Servlet receives a GET request:

public class ExampleOne extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println(
    "<!DOCTYPE html><html>" +
    "<head>" +
    "<meta charset=\"UTF-8\" />" +
    "<title>HTML Rendered by Servlet</title>" +
    "</head>" +
    "<body>" +
    "<h1>HTML Rendered by Servlet</h1></br>" +
    "<p>This page was rendered by the ExampleOne Servlet!</p>" +
    "</body>" +
    "</html>"
     );
   }
}

What we’re doing here is injecting our markup through our servlet request handling directly. Instead of a JSP tag, we generate our HTML, along with any and all Java-specific data to be inserted, purely server-side without a static JSP!

Earlier, we reviewed the out object which is a feature of JspWriter.

Above, I used the PrintWriter object instead which writes directly to the response object.

JspWriter actually buffers the string to be written into memory which is then written to the response objects after the in-memory buffer is flushed.

PrintWriter is already attached to the response object. I’ve preferred to write directly to the response object in the examples above and below for those reasons.

3.2. Java in a JSP Static Content

Here we create a JSP file named ExampleTwo.jsp with a JSP tag. As seen above, this allows Java to be added directly into our markup. Here, we randomly print an element of a String[]:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
    <head>
        <title>Java in Static Page Example</title>
    </head>
    <body>
        <h1>Java in Static Page Example</h1>
        <% 
              String[] arr = {"What's up?", "Hello", "It's a nice day today!"}; 
          String greetings = arr[(int)(Math.random() * arr.length)];    
            %>
        <p><%= greetings %></p>
    </body>
</html>

Above, you’ll see that variable declaration within JSP tags objects: type variableName and an initialization just like regular Java.

I’ve included the above example to demonstrate how to add Java to a static page without making recourse to a specific servlet. Here, Java is simply added to a page and the JSP lifecycle takes care of the rest.

3.3. JSP With Forwarding

Now, for our final and most involved example! Here, we’re going to use the @WebServlet annotation on ExampleThree which eliminates the need for servlet mappings in server.xml.

@WebServlet(
  name = "ExampleThree",
  description = "JSP Servlet With Annotations",
  urlPatterns = {"/ExampleThree"}
)
public class ExampleThree extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
      String message = request.getParameter("message");
      request.setAttribute("text", message);
      request.getRequestDispatcher("/ExampleThree.jsp").forward(request, response);
   }
}

ExampleThree takes a URL parameter passed in as message, binds that parameter to the request object, and then redirects that request object to ExampleThree.jsp.

Thus, we’ve not only accomplished a truly dynamic web experience but we’ve also done so within an application containing multiple .jsp files.

getRequestDispatcher().forward() is a simple way to ensure that the correct .jsp page is rendered.

All the data bound to the request object sent its (the .jsp file’s) way will then be displayed! Here’s how we handle that last part:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
    <head>
        <title>Java Binding Example</title>
    </head>
    <body>
        <h1>Bound Value</h1>
        <p>You said: ${text}</p>
    </body>
</html>

Note the JSP tag added to the top of ExampleThree.jsp. You’ll notice that I switched the JSP tags here. I’m using Expression Language (which I mentioned before) to render our set parameter (which is bound as ${text})!

3.4. Try It Out!

Now, we’ll export our application into a .war to be launched and hosted in Tomcat 8! Find your server.xml and we’ll update our Context to:

<Context path="/spring-mvc-xml" docBase="${catalina.home}/webapps/spring-mvc-xml">
</Context>

Which will allow us to access our servlets and JSP’s on localhost:8080/spring-mvc-xml/jsp/index.jsp! Pick up a working copy over at: GitHub. Congrats!

4. Conclusion

We’ve covered quite a bit of ground! We’ve learned about what JavaServer Pages are, what they were introduced to accomplish, their lifecycle, how to create them, and finally a few different ways to implement them!

This concludes the introduction to JSP! Be well and code on!