HttpServlet Class Example Tutorial (Java EE 10)

Java Servlets are an essential part of Java web applications, allowing for the creation of dynamic web content. One of the core components in servlet programming is the HttpServlet class, which is part of the jakarta.servlet.http package in the latest Java EE 10. This tutorial will guide you through a simple example demonstrating the usage of the HttpServlet class, focusing on handling HTTP GET and POST requests in a Todo Management application.

Introduction

The HttpServlet class, part of the jakarta.servlet.http package, extends the GenericServlet class to provide HTTP-specific methods. The two most commonly used methods in the HttpServlet class are doGet and doPost, which handle GET and POST requests, respectively.

The doGet() method is used for getting the information from the server while the doPost() method is used for sending information to the server.

In this tutorial, we will create a simple Java web application to demonstrate how to:

  1. Add a todo item using the doPost method.
  2. Retrieve and display a todo item using the doGet method based on a search operation.

Prerequisites

Before we start, ensure you have the following:

  • Basic understanding of Java Servlets and JSP.
  • Java web application development environment set up (e.g., Apache Tomcat).
  • Maven for managing project dependencies.

Project Structure

Here's the structure of our project:

httpservlet-example/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── servlet/
│   │   │               └── TodoServlet.java
│   │   ├── resources/
│   │   └── webapp/
│   │       ├── index.jsp
│   │       └── todoDetails.jsp
└── pom.xml

Dependencies

Add the necessary dependencies to your pom.xml file for the latest versions of JSP and servlet APIs:

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>3.0.0</version>
</dependency>

Creating the JSP Form Page

First, let's create a JSP page index.jsp that will collect todo data:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Todo Management</title>
</head>
<body>
    <h2>Add Todo</h2>
    <form action="todo" method="post">
        <label for="title">Title:</label>
        <input type="text" id="title" name="title" required><br><br>
        <label for="description">Description:</label>
        <input type="text" id="description" name="description" required><br><br>
        <input type="submit" value="Add Todo">
    </form>
    <h2>Search Todo</h2>
    <form action="todo" method="get">
        <label for="searchTitle">Title:</label>
        <input type="text" id="searchTitle" name="searchTitle" required><br><br>
        <input type="submit" value="Search Todo">
    </form>
</body>
</html>

Creating the Servlet Class

Next, we create the TodoServlet class to handle the form submission and display the data:

package com.example.servlet;

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.util.HashMap;
import java.util.Map;

@WebServlet("/todo")
public class TodoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Map<String, String> todos = new HashMap<>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String title = request.getParameter("title");
        String description = request.getParameter("description");

        todos.put(title, description);
        response.sendRedirect("index.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String searchTitle = request.getParameter("searchTitle");
        String todoDescription = todos.get(searchTitle);

        request.setAttribute("todoDescription", todoDescription);
        request.getRequestDispatcher("todoDetails.jsp").forward(request, response);
    }
}

Creating the JSP Display Page

Finally, create a JSP page todoDetails.jsp to display the todo details:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Todo Details</title>
</head>
<body>
    <h2>Todo Details</h2>
    <%
        String todoDescription = (String) request.getAttribute("todoDescription");
        if (todoDescription != null) {
            out.println("<p>Description: " + todoDescription + "</p>");
        } else {
            out.println("<p>No todo found with the given title.</p>");
        }
    %>
    <a href="index.jsp">Back to Home</a>
</body>
</html>

Running the Application

  1. Build the Project: Use Maven to build your project.

    mvn clean install
    
  2. Deploy to Server: Deploy the generated WAR file to your servlet container (e.g., Apache Tomcat).

  3. Access the Form: Open your browser and navigate to http://localhost:8080/httpservlet-example/index.jsp.

  4. Add a Todo: Fill in the todo form and submit.

  5. Search Todo: Use the search form to find a todo by its title and view its details.

Conclusion

In this tutorial, we explored the HttpServlet class from the jakarta.servlet.http package in Java EE 10. We demonstrated how to handle form data submission using the doPost method and how to retrieve and display form data using the doGet method in the context of a Todo Management application. This example covered adding and searching todo items to showcase the practical use of HttpServlet in a web application.

Related Servlet Posts

Comments