DEV Community

Cover image for Introduction to Java Servlets
Dilanka Rathnasiri
Dilanka Rathnasiri

Posted on

Introduction to Java Servlets

cover image: Photo by Evan Smogor on Unsplash

We are discussing the basics of Java Servlets in this article.

What is Java Servlet?

Java servlet is the Java way to develop a web application that can generate dynamic web pages. Servlets are on the server side.

What is the web container?

The web container is the interface between the servlets and the web server. All the servlets are run inside the web container. In this article, I use Apache Tomcat as the web container. Also, you can use Java EE servers like JBoss or GlassFish for running Java servlets. But Apache Tomcat is lightweight and easy to use.

Let’s build our first Java Servlet

Technologies used in this article

  • Java 11

  • Apache Maven 3.6.3

  • Apache Tomcat 10.1.7

  • IntelliJ IDEA Community Edition

Do we need IntelliJ Idea Ultimate?

No, we do not need it.

Create Maven project

Let’s generate a Maven project in batch mode. For that, enter the following command on the command line.

mvn archetype:generate -B -DgroupId="com.example" -DartifactId="servlet-example-1"
Enter fullscreen mode Exit fullscreen mode

We can change “groupId” and “artifactId” as we want. In this example project

  • groupId = com.example

  • artifactId = servlet-example-1

Project structure

We need to set up the project structure as followings.

Project structure

Modify POM file

First, we open the project from IntelliJ IDEA.

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>servlet-example-1</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>servlet-example-1</name>

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

  <dependencies>
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>6.0.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.2</version>
        <configuration>
          <webappDirectory>src/main/webapp</webappDirectory>
          <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
Enter fullscreen mode Exit fullscreen mode

The POM file of the example project is shown above. Let’s discuss each required component in the POM file.

pom.xml file

1 → We use war (web application archive) files in java servlets. Therefore, we have to set the packaging to WAR.

2 → We set the encoding system of Apache Maven to UTF-8. This is not related to the Java servlets. This is done for Apache Maven.

3 and 4 → We set the Java version to 11.

5 → Adding required “servlet-api” dependency for Java servlet. Since Apache Tomcat has all the required libraries, we set the scope to “provided”.

6 → We need “maven-war-plugin” for creating a Java WAR file.

7 → Web app directory path from the content root.

8 → web.xml file path from the content root.

Servlet App.java class source code

package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class App extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.println("Hello!");
        out.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

“HttpServlet” class provides methods for handling REST API methods such as GET, POST, PUT, and POST.

  • “doGet” method → Java method for handling GET requests

  • “doPost” method → Java method for handling POST requests

  • “doPut” method → Java method for handling PUT requests

  • “doDelete” method → Java method for handling DELETE requests

In this example project, we only used the “doGet” method. It provides a “Hello!” response for GET requests.

What is web.xml?

The web.xml file is the deployment descriptor of the project. This deployment descriptor contains information about the servlet. The deployment descriptor tells the web container how to handle the files in the servlet project.

Content of the deployment descriptor

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.example.App</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
Enter fullscreen mode Exit fullscreen mode

The web descriptor of the example project is shown above.

  • All the servlet related tags have to use inside the "" and “” tags.

  • The “” tag is used to define the name of the servlet. “” and “” tags are used inside the "" and “” tags. The “” tag is used to provide the name of the servlet. The “” tag is used to provide the Java class for the relevant servlet.

  • The “” tag is used to define the mapping of the servlet. “” and “” tags are used inside the “" and “” tags. The “” tag is used to provide the name of the servlet. The “” tag is used to provide the URL pattern of the relevant servlet.

Deploying servlet

First, we have to build the WAR file. We can do that by executing the following command in the terminal or PowerShell.

mvn clean install
Enter fullscreen mode Exit fullscreen mode

This WAR file can be deployed in Apache Tomcat. First, we have to start the Apache Tomcat. Then let’s go to the “Manager App”. In the “deploy” section, let’s click on the “Choose File” button in the “WAR file to deploy” subsection. Then let’s choose the WAR file and click on the “Deploy” button. Then, we can see the “/servlet-example-2–1.0-SNAPSHOT” in the “Application” section. Now, we can call the servlet by sending requests to “http://localhost:8080/servlet-example-2-1.0-SNAPSHOT/hello”.

Servlet Annotations

We can replace the web.xml file with annotations.

We can use “@WebServlet” annotation for “” and “” tags in web.xml. We can use the “value” attribute to define the URL pattern of the servlet. We can use the “name” attribute to define the name of the servlet.

We can rewrite App.java class with annotations as followings.

package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(
        value = "/hello",
        name = "hello"
)
public class App extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.println("Hello!");
        out.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Also, we need to change the POM file to stop searching for the web.xml file. For that, we have to change the configurations of the “maven-war-plugin” in the POM file as followings.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
Enter fullscreen mode Exit fullscreen mode




Summary

In this article, we have discussed the basics of Java Servlets with an example. We can create a Java servlet with a web.xml file or annotations. We can use Apache Tomcat for deploying Java servlet.

References

Java Tutorial Network
Introduction to Java Servlets - GeeksforGeeks
The Web Container (Your First Cup: An Introduction to the Java EE Platform)
What is a web container?

Top comments (0)