Ebooks

Java Servlet tutorial

Java Servlet tutorial shows how to create a simple servlet in Java. We use embedded Jetty server.

Java Servlet

Servlet is a Java class which responds to a network request. This is mostly an HTTP request. Java servlets are used to create web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets. For instance, Spring or Vaadin frameworks use servlets.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.

Java Servlet example

In the following example, we use the @WebServlet annotation to create a Java Servlet. Alternatively, the mapping can be created in the web.xml file.

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │               HelloServlet.java
│   ├───resources
│   └───webapp
│           index.html
└───test
    └───java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>helloservlet</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>12</maven.compiler.source>
        <maven.compiler.target>12</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.14.v20181114</version>
            </plugin>
        </plugins>
    </build>

</project>

This is the Maven POM file. The javax.servlet-api provides the Servlet API. The provided scope makes the dependency available at compile time and indicates that it is already available at runtime. In is included with the Servlet container such as Jetty.

The maven-war-plugin is responsible for collecting all artifact dependencies, classes and resources of the web application and packaging them into a web application archive. The jetty-maven-plugin allows us to run embedded Jetty server with mvn jetty:run.

com/zetcode/HelloServlet.java
package com.zetcode;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "HelloServlet", urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        response.setContentType("text/plain;charset=UTF-8");

        var out = response.getOutputStream();

        out.print("Hello there from Servlet");
    }
}

The HelloServlet returns a simple text message back to the client.

@WebServlet(name = "HelloServlet", urlPatterns = {"/hello"})

The Java class is decorated with the @WebServlet annotation. It is mapped to the hello URL pattern.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

The doGet() method is called for GET requests. The method receives HttpServletRequest and HttpServletResponse objects.

response.setContentType("text/plain;charset=UTF-8");

The servlet sends output data in plain text and the encoding of the data is set to UTF-8.

var out = response.getOutputStream();

With the getOutputStream() method, we get the servlet output stream. Note that we do not close the output stream; this is a task for the container.

out.print("Hello there from Servlet");

We write a text message with the print() method.

webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

<p>
    This is home page. Call <a href="/hello">HelloServlet</a>
</p>

</body>
</html>

In the home page, we have a link that calls the servlet.

$ mvn jetty:run

We run the embedded Jetty server and navigate the browser to localhost:8080.

In this tutorial, we have shown how to create a simple Java Servlet with embedded Jetty server.

You might also be interested in the following related tutorials: Java Socket tutorial, and Java tutorial.

List all Java tutorials.