Back to the 2025 paper

Module III: Basics of Web Programming

20257m

Describe the architecture and components of a Java Servlet.

Worked SolutionAI Assisted

Answer: Architecture, Life Cycle, and Components of a Java Servlet

1. What is a Java Servlet?

A Java Servlet is a server-side Java program running inside a Servlet Container (e.g., Apache Tomcat, Jetty, WildFly). It intercepts client requests, executes business logic, interacts with databases, and dynamically generates web responses (HTML, JSON, XML).

+-------------------+        1. HTTP Request (GET/POST)       +---------------------+
|    Web Browser    | --------------------------------------> |     Web Server      |
|     (Client)      | <-------------------------------------- |   (Apache Tomcat)   |
+-------------------+        4. HTTP Response (HTML/JSON)     +----------+----------+
                                                                         |
                                                   +---------------------v---------------------+
                                                   |             SERVLET CONTAINER             |
                                                   |                                           |
                                                   |   +-----------------------------------+   |
                                                   |   |          Servlet Instance         |   |
                                                   |   |                                   |   |
                                                   |   |  - init(ServletConfig config)     |   |
                                                   |   |  - service(req, res)              |   |
                                                   |   |      -> doGet() / doPost()        |   |
                                                   |   |  - destroy()                      |   |
                                                   |   +-----------------------------------+   |
                                                   +-------------------------------------------+

2. Servlet Life Cycle Methods

The servlet life cycle is entirely managed by the servlet container through three fundamental methods:

[Load & Instantiate] ---> [init()] ---> [service() (doGet / doPost)] ---> [destroy()]
  1. Initialization (init(ServletConfig config)):
    • Invoked once when the servlet is first loaded into memory.
    • Used for one-time initialization tasks (opening database connections, reading configuration parameters).
  2. Execution (service(ServletRequest req, ServletResponse res)):
    • Invoked for every client request in a separate worker thread.
    • For HttpServlet, the service() method dispatches the request to doGet(), doPost(), doPut(), or doDelete() based on the HTTP method.
  3. Destruction (destroy()):
    • Invoked once before the container takes the servlet instance out of service.
    • Used to release resources, close database connections, and save state.

3. Major Components of the Servlet Architecture

1. Servlet Interface (jakarta.servlet.Servlet)

  • The central root interface of all Java servlets. Declares life cycle methods (init, service, destroy, getServletConfig, getServletInfo).

2. HttpServlet Abstract Class (jakarta.servlet.http.HttpServlet)

  • Provides an HTTP-specific implementation. Subclassed by developers to handle standard HTTP verbs:
    • doGet(HttpServletRequest request, HttpServletResponse response)
    • doPost(HttpServletRequest request, HttpServletResponse response)

3. ServletConfig

  • Holds initialization parameters and configuration information specific to a single servlet instance defined in web.xml or via @WebServlet(initParams={...}).

4. ServletContext

  • Represents the broader web application context shared by all servlets in the application.
  • Used to store global application-level attributes, communicate between servlets, and access server logs.

5. HttpServletRequest & HttpServletResponse

  • HttpServletRequest: Encapsulates incoming request data (parameters, headers, cookies, form data, session).
  • HttpServletResponse: Provides methods to set response headers, status codes, cookies, and obtain an output stream (PrintWriter or ServletOutputStream) to write content back to the client.

6. HttpSession

  • Provides stateful session tracking across multiple HTTP requests for an individual user (e.g., maintaining user login or shopping cart data).

4. Example: Simple HttpServlet Implementation

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String username = request.getParameter("name");
        out.println("<!DOCTYPE html><html><body>");
        out.println("<h2>Hello, " + (username != null ? username : "Guest") + "!</h2>");
        out.println("</body></html>");
    }
}

Similar questions