Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding HttpServlet in Java Web Applications

Tech 2

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

  1. service(ServletRequest req, ServletResponse res) This method is central to the Servlet interface and is invoked for every client request. HttpServlet provides a default implementation that routes requests based on HTTP method types (GET, POST, etc.) to corresponding doXXX methods.

  2. doGet(HttpServletRequest request, HttpServletResponse response) Handles HTTP GET requests.

  3. doPost(HttpServletRequest request, HttpServletResponse response) Handles HTTP POST requests.

  4. doPut, doDelete, doOptions, doHead, doTrace These methods handle additional HTTP request types, though they are rarely used directly in typical applications.

  5. init(ServletConfig config) Invoked when a Servlet instance is loaded into memory and ready for use.

  6. destroy() Called when the Servlet instance is no longer needed and is being unloaded by the container.

HttpServlet Processing Flow

  1. Servlet Deployment

    • Developers implement a Servlet class extending HttpServlet and override relevant methods.
    • Configuration is performed in the web.xml file, specifying URL mappings and initialization parameters.
    • The web application is packaged into a WAR file and deployed to a servlet container like Tomcat.
  2. Client Request

    • A client (e.g., a browser) sends an HTTP request containing URL, method (GET, POST), headers, and body data.
  3. 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.
  4. Service Method Invocation

    • The container calls the service method on the Servlet instance with HttpServletRequest and HttpServletResponse objects.
    • The HttpServletRequest encapsulates all request details including parameters and headers.
    • The HttpServletResponse is used to build and send the HTTP response.
  5. Request Handling

    • Based on the request type (GET, POST), the service method invokes the appropriate doXXX method.
    • Business logic is implemented inside these doXXX methods, such as database access or data processing.
  6. Response Construction

    • Developers set status codes, headers, and response body using the HttpServletResponse object.
    • Content such as HTML, JSON, or XML can be written to the response body.
  7. Response Transmission

    • The container packages the HttpServletResponse into an HTTP response and transmits it back to the client.
    • The client displays the response in a browser or processes it accordingly.
  8. Lifecycle Termination

    • When the Servlet enstance becomes obsolete (e.g., during application shutdown), the container invokes the destroy method for cleanup tasks.

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.

Tags: Servlethttp

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.