We start Java EE with Servlets. In this module, we will explore the servlet container lifecycle, handle request parameters, build logins, and connect to databases using JDBC.

1.1. Java Servlet Architecture & Lifecycle Model

Definition: A Servlet is a Java class that extends the functionality of a web server by dynamically processing client HTTP requests and generating responses.

Core Working Principles:

[Client Request] ──► [Container Instantiation] ──► [init() Called] │ ▼ [destroy() Called] ◄── [Server shutdown] ◄── [doGet() / doPost() Service]
5-Marks Exam Scoring Points
  • Servlets are managed objects; the container handles instantiation and lifecycles.
  • init() runs once; service() runs on every request; destroy() runs once on shutdown.
  • Servlets run as a single instance with multiple threads (one thread per request).
  • destroy() releases open resources (like database connections) before garbage collection.

1.2. Reading Form Parameters (GET vs. POST in Servlets)

Definition: Extracting user inputs from HTTP requests inside servlets. GET and POST are the two primary HTTP methods used to send data from web forms.

Core Working Principles:

@WebServlet("/Calc")
public class CalcServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String n1 = req.getParameter("num1");
        double num1 = Double.parseDouble(n1); // Type conversion
        resp.getWriter().println("Result: " + (num1 * 2));
    }
}
5-Marks Exam Scoring Points
  • request.getParameter() extracts inputs by name.
  • Form parameters always arrive as strings and must be parsed (e.g. Integer.parseInt()).
  • GET appends data to the URL; POST sends data in the request body.
  • PrintWriter streams output HTML back to the browser.

1.3. Database Registration using JDBC and PreparedStatement

Definition: Connecting servlets to a database using JDBC to insert user records securely.

Core Working Principles:

try (Connection conn = DriverManager.getConnection(url, user, pass);
     PreparedStatement stmt = conn.prepareStatement("INSERT INTO users (name, email) VALUES (?, ?)")) {
    stmt.setString(1, req.getParameter("name"));
    stmt.setString(2, req.getParameter("email"));
    stmt.executeUpdate();
}
5-Marks Exam Scoring Points
  • DriverManager establishes a connection line to the database.
  • PreparedStatement compiles the query template, preventing SQL Injection.
  • executeUpdate() executes write transactions (INSERT, UPDATE, DELETE).
  • try-with-resources blocks automatically close database connections, preventing leaks.