Java Servlets tutorial

Java Servlets tutorial shows how to create simple servlets in Java. We create servlets using Java annotation and XML file.

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.

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

The examples use this Maven dependency. The javax.servlet-api provides the Servlet API. The provided scope makes the dependency available at compile time and indicatest that it is already available at runtime. In is included with the Servlet container (Tomcat, Jetty).

Java Servlet annotation example

In the following example, we use the @WebServlet annotation to create a Java Servlet. @WebServlet annotation can be used since Servlet 3.0 specification. The annotation is processed by the container at deployment time.

$ tree
.
├── nb-configuration.xml
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           └── web
    │   │               └── MyServlet.java
    │   ├── resources
    │   └── webapp
    │       ├── index.html
    │       ├── META-INF
    │       │   └── context.xml
    │       └── WEB-INF
    └── test
        └── java

This is the project structure.

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/JavaServletAnnotation"/>

In the Tomcat context.xml file, we define the context path. It is the name of the web application.

MyServlet.java
package com.zetcode.web;

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

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/plain;charset=UTF-8");
        
        ServletOutputStream out = response.getOutputStream();
        
        out.print("This is MyServlet");
    }
}

The MyServlet servlet returns a simple text message back to the client.

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

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

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

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

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

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

ServletOutputStream out = response.getOutputStream();

With the getOutputStream() method, we get the servlet output stream.

out.print("This is MyServlet");

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

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <a href="MyServlet">Call MyServlet</a>
    </body>
</html>

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

Java Servlet XML example

In the second example, we define two servlets in the web.xml deployment descriptor. Prior to Servlet 3.0 specification, this was the only way to define Java Servlets.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           └── web
    │   │               ├── FirstServlet.java
    │   │               └── SecondServlet.java
    │   └── webapp
    │       ├── index.html
    │       ├── META-INF
    │       │   └── context.xml
    │       └── WEB-INF
    │           └── web.xml
    └── test
        └── java

This is the project structure.

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/JavaServletXML"/>

We define the context path.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    
    <servlet>
        <servlet-name>FirstServlet</servlet-name>
        <servlet-class>com.zetcode.web.FirstServlet</servlet-class>
    </servlet>
    
    <servlet>
        <servlet-name>SecondServlet</servlet-name>
        <servlet-class>com.zetcode.web.SecondServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>FirstServlet</servlet-name>
        <url-pattern>/FirstServlet</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>SecondServlet</servlet-name>
        <url-pattern>/SecondServlet</url-pattern>
    </servlet-mapping>
    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
</web-app>

In the web.xml file, we define two Servlets: FirstServlet and SecondServlet. The web.xml is located in the WEB-INF directory.

<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.zetcode.web.FirstServlet</servlet-class>
</servlet>

We define the name and the servlet class.

<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>

We map the servlet to the URL pattern.

FirstServlet.java
package com.zetcode.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/plain;charset=UTF-8");
        
        ServletOutputStream out = response.getOutputStream();
        
        out.print("This is First Servlet");
    }
}

This is the first servlet.

SecondServlet.java
package com.zetcode.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/plain;charset=UTF-8");
        
        ServletOutputStream out = response.getOutputStream();
        
        out.print("This is Second Servlet");
    }
}

This is the second servlet.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        
        <p>
            Call <a href="FirstServlet">First Servlet</a>
        </p>
        
        <p>
            Call <a href="SecondServlet">Second Servlet</a>
        </p>    
        
    </body>
</html>

In the home page, we have two links to call both servlets.

In this tutorial, we have shown how to create simple Java Servlets.

You might also be interested in the following related tutorials: Java servlet upload file, Java Log4j tutorial, Java Servlet RESTful client, Java RequestDispatcher, Serving plain text from Java servlet, Java servlet image tutorial, or Java tutorial