Your First Servlet

Harry · 11 Sep 2026 · 9 views

Your First Servlet

Let us build a working servlet from scratch. By the end of this post you will have a deployable web application that responds to HTTP requests with dynamic content.

Project Setup

Create a Maven webapp project. The critical file is web.xml (the deployment descriptor) located at src/main/webapp/WEB-INF/web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         version="6.0">
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.example.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

This maps the URL path /hello to your HelloServlet class. When a browser visits http://localhost:8080/my-webapp/hello, Tomcat routes the request to your servlet.

The Servlet Class

Extend HttpServlet and override one of the HTTP method handlers. The doGet method handles GET requests. doPost handles POST requests.

package com.example;

import java.io.IOException;
import jakarta.servlet.http.*;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println(
            "<!DOCTYPE html>" +
            "<html><head><title>Hello</title></head>" +
            "<body><h1>Hello, World!</h1></body></html>"
        );
    }
}

Deploying to Tomcat

Run mvn clean package to produce a WAR file. Copy it to Tomcat's webapps/ directory or use the Tomcat Maven plugin with mvn tomcat7:run. Open your browser and navigate to the mapped URL.

Annotations Instead of web.xml

You can skip web.xml entirely by using the @WebServlet annotation:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet { ... }

This is cleaner for small projects. Larger applications still benefit from web.xml for centralized configuration.

Key Points

  • A servlet extends HttpServlet and overrides doGet, doPost, etc.
  • web.xml maps URL patterns to servlet classes.
  • The @WebServlet annotation provides a simpler alternative.
  • Deploy as a WAR file to Tomcat or use the Maven Tomcat plugin.
  • Set the content type with resp.setContentType() before writing output.
Share this post:

Comments (0)

Please login or register to comment.