Java Servlet and JSP Example

In this article we will demonstrate a simple Servlet and JSP example using the maven cargo plugin from the command line.

We will also cover, albeit briefly, the functioning of both Servlet and JSP constructs within the Servlet Container in terms of how they are used to satisfy a HTTP request.

The sample application will greet you with your name, supplied via query parameter or post data, and the current date on the server. The Servlet will receive the request for greeting and forward to a JSP for displaying the greeting.

1. Introduction

Java Servlets were released in 1997 as a “replacement” for the then de facto standard in dynamic web content, CGI scripts.

JSP’s were released about a year later, which was Sun’s solution to allowing HTML, XML developers to create dynamic web content using JSP technology as it did not require in depth Java knowledge.

Although architecturally the same thing (JSP is compiled into a Servlet at runtime upon first invocation) and fulfilling an equivalent function, they facilitate it in two very different ways.

A JSP allows dynamic Java delivered content to be mixed with static HTML or XML content declaratively in the same JSP page whereas a Servlet does this in a programmatic way.

2. Technologies used

The example code in this article was built and run using:

  • Java 8
  • Maven 3.3.9
  • STS (3.9.0.RELEASE)
  • Ubuntu 16.04
  • Maven cargo plugin

3. Setup

To ensure that Maven and Java are installed you can execute the following:

Confirm Java and Maven

java -version
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

mvn -version
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.8.0_101, vendor: Oracle Corporation
Java home: /home/jean-jay/runtimes/jdk1.8.0_101/jre
Default locale: en_ZA, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-42-generic", arch: "amd64", family: "unix"

4. Servlets

A servlet is a Java class which is run by a servlet container eg: Tomcat. It is capable of responding to any type of request but is more commonly known for it’s role played over the HTTP protocol.

It is typically complied once, upon first invocation and then is heavily threaded to service the plethora of client requests sent to it. Although this is the common case, once can choose to pool servlets and have a servlet per requestmodel.

A servlet has a predefined life cycle and public well known contract:

  1. Container loads the servlet mapped to the incoming request, if needed.
  2. An instance of the servlet is created.
  3. Any resources for the servlet are initialized by invoking the initmethod after which the servlet is able to service requests.
  4. Upon destruction the container will invoke the servlet’s destroymethod to clean up any resources.

5. JSP

A JSP is a hybrid of textual data (HTML, XML, SVG) and JSP elements which facilitate the delivery of dynamic content in a declarative way.

Because a JSP is compiled into a servlet, when a request is mapped to a JSP, the container will ensure that the latest version of the JSP is available in servlet form to service the request, this can involve a recompilation.

JSP also offers the JSTL as a standard way of scripting core / common functionality across JSP based applications.

6. The Program Code

In our sample application we make use of a servlet, jsp and utility class to format a greeting for a name received in a request.

Below follows snippets of the servlet, jsp and pom.xml files for the sample application.

Servlet Code

public final class Greeter extends HttpServlet {

    public static final String GREETING_REQUEST_PARAMETER_KEY = "greeting";
    private static final String NAME_REQUEST_PARAMETER_KEY = "name";

    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {

        handleRequestForGreeting(req, resp);

    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {

        handleRequestForGreeting(req, resp);

    private void handleRequestForGreeting(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        assert !Objects.isNull(req) : "Request required for greeting request";
        assert !Objects.isNull(resp) : "Response required for greeting request";

        final String name = extractNameFromRequest(req);
        final String greeting = greet(name);

        req.setAttribute(GREETING_REQUEST_PARAMETER_KEY, greeting);
        req.getRequestDispatcher("/showGreeting.jsp").forward(req, resp);

    private String extractNameFromRequest(final HttpServletRequest req) {
        assert !Objects.isNull(req) : "Request required for name extraction";

        return req.getParameter(NAME_REQUEST_PARAMETER_KEY);

    private String greet(final String name) {
        assert !Objects.isNull(name) && !name.isEmpty() : "Name required for greeting";

        return String.format("Hello %s, the date on the server is %s", name, DateFormatterUtility.format(;
  • line 1: we annotate our class as a Servlet and specify the URL it can be reached at.
  • lines 27-28: we add the recently created custom greeting to the requestobject and forward said requestto the URL mapped to the “view” JSP
  • line 34: we extract the name request parameter
  • line 40: we create a formatted greeting message

Show greeting JSP

<%@ page contentType="text/html; charset=UTF-8" %>
<h1>${requestScope.greeting == null ? "I have nothing to say" : requestScope.greeting}</h1>

line 5: we consult the request object for a greeting message and display that or I have nothing to say should no greetingmessage be present.

Maven Cargo Configuration

  • lines 7-11: Uses maven to find and download the relevant version of Tomcat (8.x) we want.
  • line 16: Configure our container to be a standalone instance and place it in a specific directory.
  • lines 24-31: We specify the artifact to deploy, type of packaging and the context path.

With the plugin approach we are able to bootstrap a Tomcat container when running our application form the command line.

Cargo , itself, is a wrapper that allows us to do programmatic manipulation of Containers in a standardized way.

7. Running the Program

To run the program, navigate to the downloaded (unzipped) project root folder and execute the following:

  • build : mvn clean install package
  • run: mvn cargo:run

Once started navigate to the following URL: localhost:8080/greet/greetme?name=JJ replacing the value JJ with a suitable alternative name.

If all goes well, you should be greeted by a page displaying the following message in bold as a heading:

Hello JJ, the date on the server is 2018 01 15

8. Summary

In this article we covered the origins of Java Servlet and JSP technology, what it is used for and how it functions. We also demonstrated a simple greeting example web application using Servlet and JSP technology.

9. Download the Source Code

This was a Java Servlet and JSP Example.

You can download the full source code of this example here: Java Servlet and JSP Example


Jean-Jay Vester graduated from the Cape Peninsula University of Technology, Cape Town, in 2001 and has spent most of his career developing Java backend systems for small to large sized companies both sides of the equator. He has an abundance of experience and knowledge in many varied Java frameworks and has also acquired some systems knowledge along the way. Recently he has started developing his JavaScript skill set specifically targeting Angularjs and also bridged that skill to the backend with Nodejs.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button