Servlet Architecture

Java Servlets are essential for creating dynamic web applications, allowing Java developers to efficiently serve client requests. In this blog post, we'll explore the architecture of Java Servlets, understand how they work, and examine their benefits over other technologies.

Introduction to Servlets

Servlets are Java programs that run on the server side and are designed to handle client requests and generate dynamic web content. Servlets are platform-independent, robust, and secure, making them a popular choice for web application development.

Benefits of Servlets

  1. Platform Independence: Written in Java, servlets can run on any platform that supports the Java Runtime Environment (JRE).
  2. Performance: Servlets create a new thread for each request, unlike CGI scripts, which create a new process for each request, resulting in better performance.
  3. Protocol Independence: Servlets can handle multiple protocols, including HTTP, FTP, and SMTP.
  4. Integration with Java APIs: Servlets can leverage the extensive set of Java APIs for various functionalities, such as database access, networking, and more.

Servlet Architecture

The servlet architecture involves several components working together to handle client requests and generate responses. Here's a step-by-step overview of the servlet architecture:

+------------+           +--------------+          +-----------+
|            |           |              |          |           |
| Web Browser|---------> |  Web Server  |--------->| Database  |
| (Client)   |  Request  |              |          |           |
|            |           |              |          |           |
+------------+           |              |          +-----------+
                         |              |
                         |              |          +-----------+
                         |              |          | Servlet 1 |
                         | Servlet      |<---------|           |
                         | Container    |          +-----------+
                         |              |
                         |              |          +-----------+
                         |              |<---------| Servlet 2 |
                         +--------------+          |           |
                                                   +-----------+

Step 1: Client Request

A client, typically a web browser, sends an HTTP request to the web server.

Step 2: Request Handling by Web Server

The web server receives the request and forwards it to the servlet container, also known as the web container or servlet engine. The servlet container manages the lifecycle of servlets.

Step 3: Servlet Container Processing

The servlet container interprets the request's URL and determines which servlet should handle it. If the servlet is not already loaded, it creates a new thread for it. If multiple requests are received for the same servlet, a separate thread is created for each request.

Step 4: Servlet Execution

The servlet processes the incoming request by interacting with the database or performing other operations. It generates a response object, which is sent back to the web server.

Step 5: Response to Client

The web server sends the response generated by the servlet back to the client, completing the request-response cycle.

Example: A Simple Feedback Form Servlet

To illustrate the servlet architecture, let's create a simple feedback form servlet. We'll develop a servlet that handles POST requests and stores the feedback data in a database.

Step 1: Create a Maven Project

First, create a new Maven project and add the following dependencies to your pom.xml file:

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>jakarta.servlet.jsp.jstl</groupId>
    <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.27</version>
</dependency>

Step 2: Create the Feedback Servlet

Create a new Java class named FeedbackServlet.java in the src/main/java/com/example/servlet directory:

package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/feedback")
public class FeedbackServlet extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/feedback_db";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "password";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Get form data
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String feedback = request.getParameter("feedback");

        // Save feedback to database
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "INSERT INTO feedback (name, email, feedback) VALUES (?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, name);
            statement.setString(2, email);
            statement.setString(3, feedback);
            int rows = statement.executeUpdate();

            if (rows > 0) {
                out.println("<h2>Thank you for your feedback!</h2>");
            } else {
                out.println("<h2>Failed to submit feedback. Please try again.</h2>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("<h2>Database connection error. Please try again later.</h2>");
        }
    }
}

Step 3: Create the Feedback Form

Create a JSP file named feedback.jsp in the src/main/webapp directory:

<!DOCTYPE html>
<html>
<head>
    <title>Feedback Form</title>
</head>
<body>
    <h2>Feedback Form</h2>
    <form action="feedback" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
        <label for="feedback">Feedback:</label><br>
        <textarea id="feedback" name="feedback" rows="4" cols="50" required></textarea><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html> 

Steps Explanation with Feedback Form Example

Client Request

The web browser (client) sends an HTTP request to the web server. In our example, the client fills out the feedback form on feedback.jsp and submits it, triggering a POST request to FeedbackServlet.

Request Handling by Web Server

The web server receives the request and forwards it to the servlet container. The servlet container manages the lifecycle of servlets and determines which servlet should handle the request based on the URL mapping.

In our example, the URL /feedback is mapped to FeedbackServlet through the @WebServlet("/feedback") annotation.

Servlet Container Processing

The servlet container interprets the request URL and creates a new thread to handle the request. If the servlet is not already loaded, the container loads it and initializes it.

In our example, the servlet container creates a thread to handle the request in FeedbackServlet.

Servlet Execution

The servlet processes the request. In FeedbackServlet, the doPost method is invoked to handle the POST request. It retrieves the form data, connects to the database, inserts the feedback data into the database, and generates a response.

Response to Client

The web server sends the response generated by the servlet back to the client. In our example, the response is an HTML page displaying a message indicating whether the feedback submission was successful or not.

out.println("<h2>Thank you for your feedback!</h2>");

Step 4: Deploy and Test

Deploy your web application to a servlet container (e.g., Tomcat) and access the feedback form via the following URL: http://localhost:8080/your-app-context/feedback.jsp.

After submitting the form, the feedback data will be saved to the database, and a confirmation message will be displayed.

Conclusion

Servlets are used l for developing dynamic web applications. Understanding the servlet architecture, including how requests are handled, processed, and responded to, is crucial for building efficient web applications. By leveraging servlets, you can create robust, scalable, and maintainable web applications with ease. Happy coding!

Comments