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:
- Instantiation: The servlet container loads the servlet class and instantiates it.
- Initialization (
init()): Runs once. Used for startup setup (like loading config parameters or database connections). - Service (
service()): Spawns a thread for each incoming request, routing it todoGet()ordoPost(). - Destruction (
destroy()): Runs once before shutdown to release resources.
[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:
- GET Method (
doGet()): Parameters are appended directly to the URL string. Insecure and has character limits. - POST Method (
doPost()): Parameters are sent inside the HTTP request body. Secure and has no length limits.
@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:
- Driver Loading: Loads the database driver into JVM memory (
Class.forName()). - Connection: Connects to the database using
DriverManager.getConnection(). - PreparedStatement: Compiles the SQL query template. We use query placeholders (
?) to prevent SQL Injection.
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.