Tutorials Logic, IN info@tutorialslogic.com

Start Servlet Setup Environment Create First Servlet

First Jakarta Servlet

A Jakarta Servlet 6.1 application runs inside a compatible servlet container. A servlet extends HttpServlet or implements Servlet, maps one or more URLs, and translates an HTTP request into a response. Application code now imports jakarta.servlet packages rather than the pre-Jakarta javax.servlet namespace.

Setup and Prerequisites

To develop Servlets you need:

  • JDK 8+ - Set JAVA_HOME environment variable
  • Apache Tomcat 9+ - Download from tomcat.apache.org
  • IDE - Eclipse EE or IntelliJ IDEA Ultimate
  • Servlet API JAR - jakarta.servlet-api-4.0.1.jar (provided by Tomcat, or add via Maven)

Maven pom.xml for Servlet Project

Maven pom.xml for Servlet Project
<?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.example</groupId>
    <artifactId>servlet-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- Servlet API (provided by Tomcat at runtime) -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- JSP API -->
        <dependency>
            <groupId>jakarta.servlet.jsp</groupId>
            <artifactId>jakarta.servlet.jsp-api</artifactId>
            <version>2.3.3</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>
            </plugin>
        </plugins>
    </build>
</project>

First Servlet - HelloServlet

HelloServlet with Annotation Mapping

HelloServlet with Annotation Mapping
package com.example;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;
import java.io.*;

// @WebServlet annotation maps this servlet to /hello URL
// Servlet 3.0+ supports annotation-based configuration
@WebServlet(
    name = "HelloServlet",
    urlPatterns = {"/hello", "/greet"},
    loadOnStartup = 1
)
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Read init parameters from web.xml or @WebInitParam
        String greeting = config.getInitParameter("greeting");
        System.out.println("Init param greeting: " + greeting);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String name = req.getParameter("name");
        if (name == null || name.trim().isEmpty()) name = "World";

        out.println("<!DOCTYPE html><html><body>");
        out.println("<h1>Hello, " + name + "!</h1>");
        out.println("<p>Request URI: " + req.getRequestURI() + "</p>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // Delegate POST to GET handler
        doGet(req, resp);
    }
}

First Servlet - HelloServlet - XML Configuration

First Servlet - HelloServlet - XML Configuration
<!-- web.xml alternative to @WebServlet annotation -->
<web-app>
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.example.HelloServlet</servlet-class>
        <init-param>
            <param-name>greeting</param-name>
            <param-value>Hello</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

Project Structure and Deployment

Build with Maven: mvn clean package - this creates a .war file in the target/ directory. Copy the WAR to Tomcat's webapps/ folder and start Tomcat. Access at http://localhost:8080/servlet-demo/hello?name=Alice.

Servlet Getting Started Project Structure

Servlet Getting Started Project Structure
servlet-demo/
├── src/main/java/com/example/
│   └── HelloServlet.java
├── src/main/webapp/
│   ├── index.html
│   └── WEB-INF/
│       └── web.xml
└── pom.xml

Minimal Deployment

Use @WebServlet for a small explicit mapping or web.xml when deployment descriptors better centralize configuration. Build against the Servlet API supplied by the container rather than packaging a second copy. Set response status, content type, and character encoding before writing the body.

Keep the servlet thin: parse and validate HTTP input, call a service, and map the result. Do not put JDBC credentials, reusable business rules, or request-specific values in servlet instance fields. Verify the exact context path and mapping when a request returns 404.

Before you move on

Start Servlet Setup Environment Create First Servlet Mastery Check

2 checks
  • Build with Maven: mvn clean package - this creates a .war file in the target/ directory.
  • Copy the WAR to Tomcat's webapps/ folder and start Tomcat.

Servlet Request Boundary

  • Shared mutable servlet fields

    A container may serve concurrent requests through one servlet instance. Keep request data local and protect any truly shared state.
Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.