GenericServlet Class Example

The GenericServlet class is an abstract class provided by the Jakarta Servlet API that implements the Servlet interface. It is designed to make it easier to create servlets by providing simple implementations of the init and destroy methods, as well as a log method for logging. Developers only need to override the service method to handle requests.

In this tutorial, we'll create an example servlet that extends the GenericServlet class to handle user feedback.

Introduction

The GenericServlet class simplifies servlet development by:

  • Providing default implementations of the init, destroy, and getServletConfig methods.
  • Offering a log method for logging messages.
  • Allowing the developer to focus on implementing the service method for handling requests.

Prerequisites

Before we start, ensure you have the following:

  • Basic understanding of Java and web development.
  • 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:

genericservlet-example/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── servlet/
│   │   │               └── FeedbackServlet.java
│   │   ├── resources/
│   │   └── webapp/
│   │       ├── WEB-INF/
│   │       └── index.jsp
└── pom.xml

Maven Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <!-- Servlet API -->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Creating the Servlet

Let's create a FeedbackServlet that extends the GenericServlet class. This servlet will handle user feedback by storing it in memory and displaying it upon request.

FeedbackServlet.java

package com.example.servlet;

import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/feedback")
public class FeedbackServlet extends GenericServlet {

    private List<String> feedbackList;

    @Override
    public void init() throws ServletException {
        feedbackList = new ArrayList<>();
        log("FeedbackServlet initialized.");
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        String feedback = req.getParameter("feedback");
        if (feedback != null && !feedback.isEmpty()) {
            feedbackList.add(feedback);
            log("Received feedback: " + feedback);
        }

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println("<html><body>");
        out.println("<h1>Feedback List</h1>");
        out.println("<ul>");
        for (String fb : feedbackList) {
            out.println("<li>" + fb + "</li>");
        }
        out.println("</ul>");
        out.println("</body></html>");
    }

    @Override
    public void destroy() {
        feedbackList = null;
        log("FeedbackServlet destroyed.");
    }
}

Explanation of Servlet Methods

init()

  • Purpose: The init method is called once when the servlet is first initialized. It is used to perform any servlet-specific initialization tasks.
  • Example in FeedbackServlet: In this example, the init method initializes an empty list to store feedback messages and logs the initialization.

service(ServletRequest req, ServletResponse res)

  • Purpose: The service method is called for each request to the servlet. It processes the request and generates a response.
  • Example in FeedbackServlet: The service method retrieves the feedback parameter from the request, adds it to the feedback list if it's not empty, and generates an HTML response displaying all feedback messages.

destroy()

  • Purpose: The destroy method is called once when the servlet is about to be destroyed. It is used to perform any cleanup tasks.
  • Example in FeedbackServlet: In this example, the destroy method sets the feedback list to null and logs the destruction.

Creating the JSP

Create a simple JSP page to submit feedback.

index.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Feedback Form</title>
</head>
<body>
    <h1>Feedback Form</h1>
    <form action="feedback" method="post">
        <label for="feedback">Enter your feedback:</label><br>
        <input type="text" id="feedback" name="feedback"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Running the Application

  1. Build your project with Maven:
    mvn clean install
    
  2. Deploy the WAR file to your servlet container (e.g., Apache Tomcat).
  3. Access the application at http://localhost:8080/genericservlet-example.

Conclusion

In this tutorial, we demonstrated how to use the GenericServlet class in a Java web application. We created a simple feedback management system to showcase the init, service, and destroy methods. By extending the GenericServlet class, we simplified servlet development and focused on handling the core logic of our application. For more complex scenarios, consider extending HttpServlet for additional HTTP-specific functionalities. For more details, refer to the official documentation.

Related Servlet Posts

Comments

Post a Comment

Leave Comment