Popular Searches
Popular Course Categories
Popular Courses

Creating Servlets Using HttpServlet

Creating Servlets Using HttpServlet

Java Servlets and Servlet Life Cycle

Creating Servlets Using HttpServlet

Course: Advanced Java Training

Topic: Creating Servlets Using HttpServlet

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Creating Servlets Using HttpServlet

HttpServlet is an abstract Java class used to create server-side components that handle HTTP requests and generate HTTP responses. It belongs to the jakarta.servlet.http package in modern Jakarta Servlet applications.

Instead of implementing every method of the basic Servlet interface, developers can extend HttpServlet and override the methods required by their applications, such as doGet() and doPost().

Servlets are commonly used to process HTML forms, display dynamic content, validate input, call business services, interact with databases, and build backend functionality for web applications.

2. Learning Objectives

  • Understand the purpose of the HttpServlet class.
  • Learn the basic structure of an HTTP servlet.
  • Create servlets using annotations and URL mappings.
  • Handle GET and POST requests.
  • Read request parameters using HttpServletRequest.
  • Generate responses using HttpServletResponse.
  • Understand servlet lifecycle methods and deployment.
  • Identify common errors and follow servlet development best practices.

3. What Is HttpServlet?

HttpServlet is a class that extends GenericServlet and provides methods designed specifically for HTTP communication. Its service() method dispatches incoming HTTP requests to appropriate handler methods based on the request method.

For example, a GET request is generally handled by doGet(), while a POST request is generally handled by doPost().

Important Characteristics

  • Supports HTTP-specific request processing.
  • Provides convenient methods for GET, POST, PUT, DELETE, HEAD, and OPTIONS requests.
  • Works within a servlet container such as Apache Tomcat.
  • Uses request and response objects to communicate with clients.
  • Can integrate with Java business logic, JDBC, and service-layer classes.
  • Supports annotation-based and deployment-descriptor-based URL mappings.

4. HttpServlet vs. GenericServlet

Feature GenericServlet HttpServlet
Purpose Provides a general, protocol-independent servlet base class. Provides HTTP-specific servlet functionality.
Package jakarta.servlet jakarta.servlet.http
Request handling Typically implements the general service() method. Provides HTTP handlers such as doGet() and doPost().
HTTP methods Does not provide the same HTTP-specific handler methods. Supports method-specific HTTP request handling.
Common use Protocol-independent servlet implementations. Web applications that communicate through HTTP.

5. Requirements for Creating an HttpServlet

Before creating a servlet, prepare the following development environment:

  • A compatible Java Development Kit (JDK).
  • An IDE such as IntelliJ IDEA, Eclipse, or another Java editor.
  • A servlet container such as Apache Tomcat.
  • A Maven or Gradle project, or another supported web application structure.
  • The Servlet API version compatible with the selected container.

Important package note: The examples below use the modern jakarta.servlet namespace. Older Java EE applications may use javax.servlet. Use the namespace that matches your server and dependencies; do not mix the two API generations in the same servlet implementation.

6. Basic Structure of an HttpServlet

A typical HTTP servlet extends HttpServlet and overrides one or more HTTP handler methods.

import java.io.IOException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

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

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Hello from MyServlet!");
    }
}

Explanation of the Code

  • HttpServlet is the parent class for HTTP request handling.
  • HttpServletRequest provides access to request data.
  • HttpServletResponse allows the servlet to construct the response.
  • doGet() handles GET requests.
  • setContentType() identifies the response format and character encoding.
  • getWriter() provides a writer for sending text to the client.

7. Creating a Servlet Using the @WebServlet Annotation

The @WebServlet annotation maps a servlet to a URL pattern. It avoids the need to declare a simple mapping in web.xml.

Example: WelcomeServlet.java

package com.example.web;

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

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {

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

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

        response.getWriter().println(
            "<!DOCTYPE html>" +
            "<html>" +
            "<head><title>Welcome</title></head>" +
            "<body>" +
            "<h1>Welcome to Java Servlets</h1>" +
            "<p>Your servlet is running successfully.</p>" +
            "</body></html>"
        );
    }
}

Understanding @WebServlet("/welcome")

The annotation tells the servlet container to map this servlet to the /welcome path within the web application.

For example, if the application is deployed with the context path myapp, the servlet can be accessed at:

http://localhost:8080/myapp/welcome

Replace myapp with the actual deployed application context path.

8. Handling GET Requests with doGet()

The doGet() method is commonly used to retrieve or display information. A GET request should be safe and should not perform actions that modify server-side state in ways the user is responsible for, such as deleting a record.

Example: Displaying a Message

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

@WebServlet("/message")
public class MessageServlet extends HttpServlet {

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

        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("This message was generated by a servlet.");
    }
}

How It Works

  1. The browser requests the mapped URL.
  2. The servlet container finds MessageServlet.
  3. The container dispatches the GET request to doGet().
  4. The servlet creates a plain-text response.
  5. The browser displays the returned message.

9. Reading Query Parameters in a Servlet

Query parameters are values sent in the URL after a question mark. They can be retrieved using request.getParameter().

Example URL

http://localhost:8080/myapp/greet?name=Aarav

GreetingServlet.java

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

@WebServlet("/greet")
public class GreetingServlet extends HttpServlet {

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

        String name = request.getParameter("name");

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

        if (name == null || name.isBlank()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().println("Please provide a name.");
            return;
        }

        response.getWriter().println("Hello, " + name + "!");
    }
}

Important: Request parameters are untrusted input. Validate data before using it in application logic. If displaying user input in HTML, use appropriate output encoding to prevent cross-site scripting (XSS).

10. Handling POST Requests with doPost()

The doPost() method is commonly used to process submitted form data and other requests that carry data in the request body.

HTML Form Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>User Registration</title>
</head>
<body>
    <h2>User Registration</h2>
    <form action="register" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <button type="submit">Register</button>
    </form>
</body>
</html>

RegistrationServlet.java

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

@WebServlet("/register")
public class RegistrationServlet extends HttpServlet {

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

        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");

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

        if (username == null || username.isBlank()) {
            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Username is required."
            );
            return;
        }

        response.getWriter().println("Registration request received.");
    }
}

This example validates the submitted username and returns a response. In a complete registration application, the servlet should call a service component to perform the required business operation, rather than putting all application logic directly into the servlet.

11. Understanding HttpServletRequest and HttpServletResponse

HttpServletRequest

The request object provides access to information about the incoming HTTP request.

Method Purpose
getParameter("name") Retrieves a request parameter.
getMethod() Returns the HTTP request method.
getRequestURI() Returns the request URI.
getHeader("User-Agent") Reads a request header.
getSession() Obtains or creates an HTTP session.
getParameterValues("skills") Retrieves multiple values for a parameter.

HttpServletResponse

The response object is used to construct the HTTP response sent to the client.

Method Purpose
setContentType() Sets the response content type.
setStatus() Sets the HTTP status code.
sendError() Sends an error response.
sendRedirect() Redirects the client to another URL.
getWriter() Obtains a writer for text output.
getOutputStream() Obtains an output stream for binary content.

12. Understanding the HttpServlet Lifecycle

The servlet container manages the lifecycle of an HttpServlet instance.

  1. Loading and instantiation: The container loads the class and creates an instance.
  2. Initialization: The container invokes init() before the servlet handles requests.
  3. Request processing: The container calls service(), which dispatches HTTP requests to handlers such as doGet() and doPost().
  4. Destruction: The container invokes destroy() when the servlet is being taken out of service.
  5. Memory reclamation: The JVM may later reclaim the instance when it is no longer referenced.

Example of init() and destroy()

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

@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("Servlet initialized.");
    }

    @Override
    public void destroy() {
        System.out.println("Servlet is being taken out of service.");
    }
}

Use lifecycle methods for appropriate setup and cleanup tasks. Do not assume that a servlet instance will be initialized only when a user first visits a page; startup behavior depends on container configuration.

13. Configuring a Servlet Using web.xml

Servlets can also be configured through the deployment descriptor, commonly called web.xml. This approach can be useful when an application needs centralized deployment configuration.

Example web.xml Configuration

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
         https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">

    <servlet>
        <servlet-name>WelcomeServlet</servlet-name>
        <servlet-class>com.example.web.WelcomeServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>WelcomeServlet</servlet-name>
        <url-pattern>/welcome</url-pattern>
    </servlet-mapping>

</web-app>

The XML schema and version must match the Servlet API supported by the target container. Do not add duplicate or conflicting mappings for the same servlet path.

14. Deploying and Running a Servlet

  1. Create a Java web application project in your IDE or using Maven.
  2. Add a compatible Servlet API dependency.
  3. Create a class that extends HttpServlet.
  4. Map the servlet using @WebServlet or web.xml.
  5. Compile and package the application, commonly as a WAR file.
  6. Deploy the application to a compatible servlet container such as Apache Tomcat.
  7. Start the container and check its logs for deployment errors.
  8. Open the servlet's mapped URL in a browser or test it with an HTTP client.

For Maven projects, the Servlet API dependency is usually declared with provided scope because the servlet container supplies the API at runtime.

Example Maven Dependency

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

Choose the dependency version according to the Java version and servlet container you are using. For example, a container supporting Servlet 6.0 uses the Jakarta Servlet 6.0 API; older containers may require a different API generation.

15. Common Errors and Troubleshooting

Problem Possible Cause Solution
HTTP 404 Not Found Incorrect URL, context path, or mapping. Verify the deployed application name and servlet URL pattern.
HTTP 405 Method Not Allowed The servlet does not handle the requested HTTP method. Implement the appropriate handler, such as doPost(), if needed.
ClassNotFoundException Incorrect class name, package, or deployment output. Check the package declaration and compiled application files.
Servlet API class not found Missing dependency or incompatible API/container version. Use a compatible servlet container and API dependency.
HTTP 500 Internal Server Error Unhandled exception or server-side failure. Review server logs and handle expected exceptions.
Request parameter is null Incorrect form field name or missing submitted value. Check the input element's name attribute and request method.
Incorrect character display Character encoding was not configured appropriately. Set the appropriate request and response encoding before reading or writing content.

16. Best Practices for Creating HttpServlets

  • Use a servlet container that supports the Servlet API version selected for the project.
  • Use doGet() for safe retrieval operations and doPost() for appropriate submission operations.
  • Set the response content type and character encoding before obtaining the writer.
  • Validate all request parameters on the server.
  • Use parameterized SQL statements when accessing a database.
  • Keep business logic in service classes and database code in DAO or repository classes.
  • Avoid storing request-specific mutable data in servlet instance fields because a servlet may handle concurrent requests.
  • Use HTTPS and appropriate authentication, authorization, and CSRF protection for sensitive operations.
  • Do not expose passwords, stack traces, or confidential information in user-facing error messages.
  • Use logging and tests to diagnose failures.
  • Do not override the service() method unnecessarily; prefer overriding the appropriate HTTP handler methods.

17. Mini Project: Simple Employee Information Servlet

Project Objective: Create a servlet that accepts an employee ID and returns a response indicating whether the ID was provided correctly. This project introduces URL mapping, GET request handling, parameter validation, and HTTP responses.

EmployeeServlet.java

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

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {

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

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

        String employeeId = request.getParameter("id");

        if (employeeId == null || employeeId.isBlank()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().println("Employee ID is required.");
            return;
        }

        try {
            int id = Integer.parseInt(employeeId);

            if (id <= 0) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Employee ID must be positive.");
                return;
            }

            response.getWriter().println(
                "Employee ID received: " + id
            );

        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().println("Employee ID must be a number.");
        }
    }
}

Testing the Servlet

After deploying the application, open a URL such as:

http://localhost:8080/myapp/employee?id=101

The servlet validates the employee ID and returns a response. An extended version can call an employee service that retrieves the employee's details from a database using JDBC.

Project Extensions

  • Create a form for searching employees.
  • Add a POST servlet for creating employee records.
  • Connect the application to a database through a DAO class.
  • Return appropriate status codes for missing or invalid records.
  • Add unit or integration tests for valid and invalid requests.

18. Interview Questions and Answers

Q1. What is HttpServlet?

HttpServlet is an abstract class that provides HTTP-specific functionality for building Java servlets.

Q2. Why do developers extend HttpServlet?

Developers extend it to implement handlers such as doGet() and doPost() without implementing the complete Servlet interface themselves.

Q3. What is the purpose of doGet()?

doGet() handles HTTP GET requests, which are commonly used to retrieve or display information.

Q4. What is the purpose of doPost()?

doPost() handles HTTP POST requests, which are commonly used to submit data to the server for processing.

Q5. What is @WebServlet?

@WebServlet is an annotation used to configure a servlet and map it to one or more URL patterns.

Q6. What is HttpServletRequest?

It provides access to the HTTP request, including parameters, headers, and session information.

Q7. What is HttpServletResponse?

It is used to set response headers and status codes and write content back to the client.

Q8. What is the difference between doGet() and service()?

The container invokes service() to process a request. In HttpServlet, the HTTP-specific service implementation dispatches the request to methods such as doGet() or doPost().

Q9. Can a servlet handle multiple requests?

Yes. A servlet container may process multiple requests concurrently using the same servlet instance, so shared mutable state must be managed carefully.

Q10. What is the difference between annotation-based mapping and web.xml mapping?

Annotation-based mapping uses annotations such as @WebServlet in Java code, whereas web.xml defines mappings in the application's deployment descriptor.

Q11. Why should the response content type be set before getWriter()?

Setting the content type first ensures that the response headers are configured before the response body is written or committed.

Q12. What is the difference between javax.servlet and jakarta.servlet?

They are package namespaces associated with different Servlet API generations. Use imports, dependencies, and a container that belong to the same compatible API generation.

19. Practice Exercises

  1. Create a servlet that displays a welcome message using doGet().
  2. Create a servlet mapped to /about and return a plain-text response.
  3. Read a name parameter from a query string and validate it.
  4. Create an HTML form that submits data to a servlet using POST.
  5. Return an appropriate HTTP 400 response when required input is missing.
  6. Implement init() and destroy() to understand lifecycle events.
  7. Configure one servlet using @WebServlet and another using web.xml.
  8. Build an employee search servlet that calls a service and DAO layer.
  9. Review your servlet for thread-safety and input-validation problems.

20. Quick Revision Checklist

  • Understand the purpose of HttpServlet.
  • Know the difference between GenericServlet and HttpServlet.
  • Create a servlet by extending HttpServlet.
  • Map a servlet using @WebServlet or web.xml.
  • Handle GET requests with doGet().
  • Handle POST requests with doPost().
  • Read parameters with HttpServletRequest.
  • Write responses using HttpServletResponse.
  • Understand servlet lifecycle and concurrency.
  • Use compatible API dependencies and a suitable servlet container.
  • Validate user input and follow secure development practices.

21. Official Documentation and Further Learning

22. Conclusion

Creating servlets using HttpServlet is a core skill in Advanced Java web development. By extending the class, mapping a URL, implementing HTTP handler methods, reading request data, and writing appropriate responses, developers can build the server-side foundation of Java web applications.

Understanding request processing, servlet lifecycle, API compatibility, deployment, and thread safety makes it easier to develop maintainable applications and progress toward topics such as JDBC integration, session management, filters, JSP, and REST API development.

To continue learning enterprise Java development, explore the Advanced Java Training Course at JustAcademy, register for a course demo, or visit the JustAcademy Homepage.

Previous Next
whatsapp