🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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, andgetServletConfigmethods. - Offering a
logmethod for logging messages. - Allowing the developer to focus on implementing the
servicemethod 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
initmethod 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
initmethod initializes an empty list to store feedback messages and logs the initialization.
service(ServletRequest req, ServletResponse res)
- Purpose: The
servicemethod is called for each request to the servlet. It processes the request and generates a response. - Example in FeedbackServlet: The
servicemethod 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
destroymethod 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
destroymethod 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
- Build your project with Maven:
mvn clean install - Deploy the WAR file to your servlet container (e.g., Apache Tomcat).
- 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
- Servlet Life Cycle
- Servlet Interface Example
- GenericServlet Class Example
- HttpServlet Class Example Tutorial
- HttpServlet doGet() Method Example
- HttpServlet doPost() Method Example
- @WebServlet Annotation Example
- @WebInitParam Annotation Example
- @WebListener Annotation Example
- @WebFilter Annotation Example
- @MultipartConfig Annotation Example
- How to Return a JSON Response from a Java Servlet
- Servlet Registration Form + JDBC + MySQL Database Example
- Login Form Servlet + JDBC + MySQL Example
- Servlet JDBC Eclipse Example Tutorial
- JSP Servlet JDBC MySQL CRUD Example Tutorial
- Servlet + JSP + JDBC + MySQL Example
- Registration Form using JSP + Servlet + JDBC + Mysql Example
- Login Form using JSP + Servlet + JDBC + MySQL Example
- JSP Servlet Hibernate CRUD Example
- JSP Servlet Hibernate Web Application
- Hibernate Registration Form Example with JSP, Servlet, MySQL
- Login Form using JSP + Servlet + Hibernate + MySQL Example
This the best and easy way tuturial, I loved It...
ReplyDelete