Servlet
interface from the jakarta.servlet
package defines the essential methods that all servlets must implement. This tutorial will guide you through an example demonstrating the Servlet
interface and its primary methods.For more detailed information, refer to the official documentation.
Introduction
The Servlet
interface defines methods to initialize a servlet, process requests, and perform cleanup. The three main methods are:
init(ServletConfig config)
: Called once when the servlet is initialized.service(ServletRequest req, ServletResponse res)
: Called to handle each request.destroy()
: Called once when the servlet is about to be destroyed.
In this tutorial, we will create a simple servlet to manage and display user feedback using the Servlet
interface.
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:
servlet-interface-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 implements the Servlet
interface. 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.Servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class FeedbackServlet implements Servlet {
private ServletConfig config;
private List<String> feedbackList;
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
feedbackList = new ArrayList<>();
}
@Override
public ServletConfig getServletConfig() {
return config;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
String feedback = req.getParameter("feedback");
if (feedback != null && !feedback.isEmpty()) {
feedbackList.add(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 String getServletInfo() {
return "FeedbackServlet";
}
@Override
public void destroy() {
feedbackList = null;
}
}
Explanation of Servlet Methods
init(ServletConfig config)
- 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.
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, effectively releasing any resources used by the servlet.
Configuring the Servlet
Instead of using the web.xml
file, we will use annotations to configure the servlet.
Complete FeedbackServlet with Annotations
package com.example.servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/feedback")
public class FeedbackServlet extends HttpServlet {
private List<String> feedbackList;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
feedbackList = new ArrayList<>();
}
@Override
protected void doPost(ServletRequest req, ServletResponse res) throws ServletException, IOException {
String feedback = req.getParameter("feedback");
if (feedback != null && !feedback.isEmpty()) {
feedbackList.add(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;
}
}
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/servlet-interface-example
.
Conclusion
This tutorial demonstrated how to implement the Servlet
interface in a Java web application using the Jakarta Servlet API. We created a simple feedback management system to showcase the init
, service
, and destroy
methods. For more advanced applications, consider extending HttpServlet
and using its built-in methods for handling HTTP-specific functionalities.
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
Comments
Post a Comment
Leave Comment