Understanding HttpServlet in Java Web Applications
Overview of Servlet and HttpServlet
A Servlet is an interface defined in the Java Servlet API that enables web servers to extend their capabilities. It's a Java program that runs within a web or application server and can dynamically generate web pages or other types of responses.
HttpServlet Class
The HttpServlet class serves as a core component in the Java Servlet API. It inherits from GenericServlet and implements the Servlet interface, offering specific implementations tailored for HTTP protocols. Its primary role involves handling HTTP requests and constructing appropriate responses.
Key Methods in HttpServlet
-
service(ServletRequest req, ServletResponse res) This method is central to the Servlet interface and is invoked for every client request.
HttpServletprovides a default implementation that routes requests based on HTTP method types (GET, POST, etc.) to correspondingdoXXXmethods. -
doGet(HttpServletRequest request, HttpServletResponse response) Handles HTTP GET requests.
-
doPost(HttpServletRequest request, HttpServletResponse response) Handles HTTP POST requests.
-
doPut, doDelete, doOptions, doHead, doTrace These methods handle additional HTTP request types, though they are rarely used directly in typical applications.
-
init(ServletConfig config) Invoked when a Servlet instance is loaded into memory and ready for use.
-
destroy() Called when the Servlet instance is no longer needed and is being unloaded by the container.
HttpServlet Processing Flow
-
Servlet Deployment
- Developers implement a Servlet class extending
HttpServletand override relevant methods. - Configuration is performed in the
web.xmlfile, specifying URL mappings and initialization parameters. - The web application is packaged into a WAR file and deployed to a servlet container like Tomcat.
- Developers implement a Servlet class extending
-
Client Request
- A client (e.g., a browser) sends an HTTP request containing URL, method (GET, POST), headers, and body data.
-
Container Dispatching
- The servlet container receives the request, parses the URL path, and identifies the matching Servlet instance.
- If the instance doesn't exist, it creates one.
-
Service Method Invocation
- The container calls the
servicemethod on the Servlet instance withHttpServletRequestandHttpServletResponseobjects. - The
HttpServletRequestencapsulates all request details including parameters and headers. - The
HttpServletResponseis used to build and send the HTTP response.
- The container calls the
-
Request Handling
- Based on the request type (GET, POST), the
servicemethod invokes the appropriatedoXXXmethod. - Business logic is implemented inside these
doXXXmethods, such as database access or data processing.
- Based on the request type (GET, POST), the
-
Response Construction
- Developers set status codes, headers, and response body using the
HttpServletResponseobject. - Content such as HTML, JSON, or XML can be written to the response body.
- Developers set status codes, headers, and response body using the
-
Response Transmission
- The container packages the
HttpServletResponseinto an HTTP response and transmits it back to the client. - The client displays the response in a browser or processes it accordingly.
- The container packages the
-
Lifecycle Termination
- When the Servlet enstance becomes obsolete (e.g., during application shutdown), the container invokes the
destroymethod for cleanup tasks.
- When the Servlet enstance becomes obsolete (e.g., during application shutdown), the container invokes the
Service Method Implementation
The service method acts as the entry point for handling different HTTP methods in the Servlet container. Upon receiving a request, the container determines the HTTP method and calls the corresponding doXXX method.
Here is the implementation of the service method in HttpServlet:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("Cannot cast to HttpServletRequest/HttpServletResponse");
}
String method = request.getMethod();
if (method.equalsIgnoreCase("GET")) {
long lastModified = getLastModified(request);
if (lastModified == -1) {
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
} else {
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
maybeSetLastModified(response, lastModified);
} else {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
doGet(request, response);
} else if (method.equalsIgnoreCase("HEAD")) {
long lastModified = getLastModified(request);
maybeSetLastModified(response, lastModified);
doHead(request, response);
} else if (method.equalsIgnoreCase("POST")) {
doPost(request, response);
} else if (method.equalsIgnoreCase("PUT")) {
doPut(request, response);
} else if (method.equalsIgnoreCase("DELETE")) {
doDelete(request, response);
} else if (method.equalsIgnoreCase("OPTIONS")) {
doOptions(request, response);
} else if (method.equalsIgnoreCase("TRACE")) {
doTrace(request, response);
} else {
throw new ServletException("HTTP method " + method + " is not supported");
}
}
This method first validates that the input request and response objects can be cast to their HTTP-specific counterparts. Then, it retrieves the HTTP method and dispatches the call to the corresponding doXXX method. For GET requests, it also checks for conditional headers to determine whether to send a 304 Not Modified response.
Unsupported HTTP methods result in a ServletException. Typically, developers override doGet, doPost, and similar methods to define custom business logic while the service method handles routing.
Example Code
Below is a basic example demonstrating how to process a GET request using HttpServlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
response.getWriter().write(htmlContent);
}
}
In this example, MyServlet extends HttpServlet and overrides the doGet() method. When a GET request is received, the container calls doGet() to process it. Inside doGet(), we set the response content type to HTML and write a simple HTML message to the output stream.