Introduction to Servlets: A Complete Guide with Examples and Best Practices

What is a Servlet?

A Servlet is a Java class that runs on a server, processes requests (usually HTTP), and generates dynamic responses. It acts as a bridge between a client (browser) and a server, facilitating interaction in web applications.

Key Features of Servlets:

  1. Platform-Independent: Write once, run anywhere (on any Java-supported server).
  2. Scalable: Handles multiple client requests using multithreading.
  3. Dynamic Content: Creates responses based on user input or data from databases.

How Servlets Fit into Java EE

Servlets are a core component of the Java Platform, Enterprise Edition (Java EE), designed to build robust, scalable, and secure web applications.

Role of Servlets in Java EE Architecture:

  • Presentation Layer: Handles HTTP requests and responses.
  • Middleware: Servlets work as the controller in the Model-View-Controller (MVC) architecture, processing logic and delegating presentation tasks to JSP or frontend frameworks.
  • Integration: Works seamlessly with databases, Enterprise JavaBeans (EJB), and other Java EE technologies.

Advantages of Using Servlets

  • Performance: Servlets are faster than CGI scripts because they are compiled into Java bytecode and run in a single process.
  • Robustness: Built on Java, servlets offer exception handling and type safety.
  • Ease of Use:
    • Session Management: Supports sessions for maintaining user-specific data.
    • Request Handling: Provides a simple API for handling HTTP GET and POST methods.
  • Integration with Java EE:
    • Works seamlessly with JSP, JDBC, EJB, and other Java technologies.
  • Security:
    • Supports HTTPS, authentication, and encryption.
  • Portability: Servlets can run on any Java EE-compliant server, ensuring platform independence.

What is CGI (Common Gateway Interface)?

The Common Gateway Interface (CGI) is a standard protocol used to enable interaction between a web server and external programs or scripts. It allows servers to execute scripts written in various languages like Perl, Python, or C, generating dynamic web content.

How CGI Works

  1. The client sends an HTTP request to the server.
  2. The web server identifies a CGI script to handle the request.
  3. The server launches a new process to execute the script.
  4. The script generates a response, which is sent back to the client.

    Diagram: How CGI Works

Client Browser
      |
      v
  Web Server
      |
      v
  CGI Script
      |
      v
Generated Response

Difference Between CGI and Servlets

AspectCGIServlets
TechnologyLanguage-independent (Perl, Python, C, etc.).Java-based technology.
PerformanceCreates a new process for each request, leading to high overhead.Uses threads to handle requests within the same process, making it faster.
ScalabilityLimited scalability due to high resource consumption.Highly scalable due to efficient multithreading.
Platform DependencePlatform-dependent scripts; portability may vary.Platform-independent due to Java’s “write once, run anywhere” nature.
IntegrationDoes not integrate seamlessly with modern technologies like databases and APIs.Easily integrates with Java EE technologies like JDBC, EJB, and JSP.
State ManagementLacks built-in session management; requires external mechanisms.Supports HTTP sessions and cookies natively.
SecurityVulnerable to various security risks if not handled properly (e.g., script injection).Offers built-in security features like HTTPS, authentication, and encryption.
MaintenanceScripts can become unmanageable for large applications.Easier to maintain due to Java’s robust libraries and frameworks.

Diagram: Comparison of CGI and Servlet Architecture CGI Architecture

Client Browser
      |
      v
  Web Server
      |
      v
  [New Process]
  CGI Script Execution

Servlet Architecture

Client Browser
      |
      v
  Web Server
      |
      v
Servlet Container (Single Process)
   |     |     |
  Thread Thread Thread (Handles Multiple Requests)

Key Takeaways

  • CGI is outdated and resource-intensive, as it spawns a new process for each request.
  • Servlets leverage Java’s multithreading model, offering better performance, scalability, and maintainability.
  • For modern web applications, servlets (or servlet-based frameworks like Spring and Struts) are preferred over CGI due to their robust feature set and compatibility with Java EE.

If you’re building a dynamic, scalable web application, Servlets are the clear choice over CGI.

Step-by-Step Example: Processing User Input

HTML Form

<form method="POST" action="input">
    Name: <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

Servlet to Handle Input

@WebServlet("/input")
public class InputServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        response.setContentType("text/html");
        response.getWriter().write("<h1>Welcome, " + name + "!</h1>");
    }
}

Best Practices for Using Servlets

  • Follow the MVC Pattern: Use servlets as controllers and JSP for the view.
  • Minimize Shared State: Avoid using shared variables to ensure thread safety.
  • Error Handling:
    • Provide meaningful error messages.
    • Use custom error pages in web.xml.
  • Use Annotations:
    • Prefer @WebServlet over XML configurations for simplicity.
  • Reuse Resources:
    • Use connection pooling for database access.
    • Avoid redundant resource creation in the service() method.
  • Secure Your Servlets:
    • Validate user inputs.
    • Use HTTPS and secure cookies for sensitive operations.