1. Different Ways to Create a Servlet
In Java, there are several ways to create a servlet, which is essentially a Java class that extends `HttpServlet` to handle HTTP requests and responses. Below are the primary ways to create a servlet:
1. Extending the HttpServlet Class
The most common and standard approach for creating a servlet is to extend the `HttpServlet` class and override its methods, such as `doGet()` and `doPost()`, to handle HTTP requests.
This method allows you to define how the servlet responds to different types of HTTP requests, such as GET, POST, PUT, DELETE, etc.
Steps to Create a Servlet by Extending HttpServlet:
- Extend the `HttpServlet` class.
- Override the `doGet()` and/or `doPost()` method to process client requests.
- Register the servlet in the `web.xml` file or use annotations to map the servlet to a URL.
Example Code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, World!</h1></body></html>");
}
}
In this example, the servlet extends `HttpServlet` and overrides the `doGet()` method to respond with "Hello, World!" when accessed via a GET request.
2. Implementing the Servlet Interface
Instead of extending `HttpServlet`, you can directly implement the `Servlet` interface. This approach requires you to implement all the methods defined in the `Servlet` interface, such as `init()`, `service()`, and `destroy()`.
This method gives you more control over the lifecycle of the servlet but is less common than extending `HttpServlet`.
Steps to Create a Servlet by Implementing the Servlet Interface:
- Implement the `Servlet` interface.
- Provide implementations for the `init()`, `service()`, and `destroy()` methods.
- Register the servlet in the `web.xml` file or use annotations to map the servlet to a URL.
Example Code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException { }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, World!</h1></body></html>");
}
public void destroy() { }
public ServletConfig getServletConfig() { return null; }
public String getServletInfo() { return "MyServlet"; }
}
In this example, the servlet implements the `Servlet` interface directly and provides the required methods. The `service()` method handles the HTTP request and response.
3. Using the GenericServlet Class
Another option is to create a servlet by extending the `GenericServlet` class. This class implements the `Servlet` interface but provides default implementations for some methods like `init()` and `destroy()`. You only need to override the `service()` method to handle requests.
This approach is less common, as the `HttpServlet` class is more specialized for HTTP requests. However, you can use it if you need a generic servlet that does not specifically handle HTTP requests.
Steps to Create a Servlet Using GenericServlet:
- Extend the `GenericServlet` class.
- Override the `service()` method to process requests.
- Register the servlet in the `web.xml` file or use annotations to map the servlet to a URL.
Example Code:
import javax.servlet.*;
import java.io.*;
public class MyGenericServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, Generic Servlet!</h1></body></html>");
}
}
In this example, the servlet extends `GenericServlet` and overrides the `service()` method to handle requests.
Summary
The four primary ways to create a servlet in Java are:
- Extending HttpServlet: The most common way, where you override methods like `doGet()` and `doPost()`.
- Implementing the Servlet Interface: Directly implementing the `Servlet` interface and providing implementations for all required methods.
- Using Annotations (Servlet 3.0 and Above): Using the `@WebServlet` annotation for URL mapping, eliminating the need for `web.xml` configuration.
- Using GenericServlet: Extending `GenericServlet` and overriding the `service()` method for handling requests.
2. Servlet Hierarchy
The servlet hierarchy defines the relationships between various classes and interfaces in the Servlet API:
- Servlet Interface: The root interface for all servlets. It defines lifecycle methods like
init(),service(), anddestroy(). - GenericServlet: An abstract class that provides a generic, protocol-independent implementation of the Servlet interface.
- HttpServlet: A subclass of GenericServlet that provides HTTP-specific methods like
doGet()anddoPost().
Servlet (Interface)
|
+-- GenericServlet (Abstract Class)
|
+-- HttpServlet (Class)
3. HttpServletRequest and HttpServletResponse
3.1 HttpServletRequest
This interface represents the client's request and provides methods to retrieve:
- Request parameters:
getParameter(String name) - Request headers:
getHeader(String name) - Session information:
getSession() - Client data:
getRemoteAddr(),getRemoteHost()
3.2 HttpServletResponse
This interface represents the server's response and provides methods to:
- Set content type:
setContentType(String type) - Write response data:
getWriter() - Set HTTP status codes:
setStatus(int code) - Send redirects:
sendRedirect(String location)
4. Difference Between GenericServlet and HttpServlet
| Aspect | GenericServlet | HttpServlet |
|---|---|---|
| Protocol | Protocol-independent. | Designed for HTTP protocol. |
| Methods | Overrides service(). |
Provides doGet(), doPost(), and other HTTP-specific methods. |
| Use Case | For non-HTTP protocols or generic tasks. | For web applications using HTTP. |
| Ease of Use | Less convenient for HTTP-specific tasks. | Optimized for handling HTTP requests and responses. |