Saturday, 29 March 2014

Servlets : Webserver vs Application Server

🚀 Master Java & Servlets with Ram N Java!

Subscribe to get clear, beginner-friendly tutorials right when they drop.

🔔 Subscribe to Ram N Java

Web Server vs. Application Server

One of the most frequent points of confusion for backend developers is distinguishing between a Web Server and an Application Server. While both process incoming network requests and deliver content back to clients, they serve fundamentally different roles across enterprise architecture.

In this guide, unpack the key architectural differences, supported protocols, execution environments, and popular industry examples.

Core Differences at a Glance

Feature Web Server Application Server
Primary Function Delivers static web content (HTML, CSS, images). Executes business logic, generates dynamic content.
Protocols Primarily HTTP and HTTPS. HTTP/S, RMI, IIOP, JMS, and RPC protocols.
Technologies Static files, reverse proxying, URL redirection. Servlets, JSPs, EJB, JPA, JMS transactions.
Examples Apache HTTP Server, Nginx, Microsoft IIS. Apache Tomcat (Servlet container), WildFly, WebLogic.

How They Work Together

In real-world enterprise architectures, web servers and application servers typically complement each other rather than compete:

  • The Web Server (e.g., Nginx) acts as the front-facing reverse proxy and load balancer, rapidly delivering static assets and terminating SSL/TLS.
  • Requests requiring business computations or database persistence are forwarded to the Application Server (e.g., Tomcat), which executes the Java Servlet lifecycle and passes the response back.

Recommended Next Watch

Continue mastering Java web development fundamentals with these lessons:


Click here to watch in Youtube : https://www.youtube.com/watch?v=WkaLSZ888as

Click the below Image to Enlarge
Webserver vs Application Server
See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Servlets : Application Server

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is an Application Server?

    An Application Server is a specialized software framework that provides an environment in which web applications can run, execute complex business logic, manage transactions, and connect to enterprise databases.

    While a standard web server is optimized for delivering static files like HTML, images, and style sheets, an application server exposes business logic to client applications using various protocols and runtime environments, such as Java EE / Jakarta EE containers.

    Core Functions of an Application Server

    • Business Logic Execution: Coordinates application operations, calculations, and rules across backend components like Java Servlets, JSPs, and EJBs.
    • Resource & Connection Management: Manages database connection pools, thread pools, and messaging queues efficiently to maximize throughput.
    • Transaction & Security Services: Offers built-in support for distributed ACID transactions, user authentication, role-based access control, and data encryption.
    • High Availability & Clustering: Provides session replication, clustering, and failover capabilities across enterprise production environments.

    Popular Java Application Servers

    • Apache Tomcat: A lightweight, highly popular open-source servlet container implementing Java Servlet and JSP specifications.
    • WildFly (formerly JBoss): A full-featured, open-source Jakarta EE application server managed by Red Hat.
    • Oracle WebLogic & IBM WebSphere: Enterprise-tier application servers designed for large-scale distributed mission-critical systems.

    Recommended Next Watch

    Continue exploring server architecture and core Java web development topics:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=ntQlB2fWyE0

    Click the below Image to Enlarge
    Application Server
    Application Server
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Servlets : ServletLifeCycle - Example

    Enjoying Java & Servlet Tutorials?

    Subscribe to Ram N Java for in-depth, beginner-friendly programming guides!

    Subscribe Now

    Understanding the Servlet Life Cycle in Java

    In Java web development, understanding the life cycle of a Servlet is fundamental. The entire life cycle of a Servlet is managed by the Servlet Container (such as Apache Tomcat) and consists of three core methods: init(), service(), and destroy().

    1. Initialization Phase: init()

    The init() method is invoked by the container strictly once when the Servlet instance is first loaded and instantiated. This phase initializes necessary resources, configurations, or database connections before handling client requests.

    2. Request Processing Phase: service()

    Once initialized, the service() method is executed multiple times—each time a client sends a request to the mapped URL pattern. It reads incoming client requests and generates dynamic responses back to the browser.

    3. Destruction Phase: destroy()

    The destroy() method is called by the container strictly once when the Servlet is taken out of service or the server is shutting down. This allows clean-up operations like closing database connections or releasing system memory.


    Related Tutorials from the Channel


    Click here to watch in Youtube : https://www.youtube.com/watch?v=6AcVTFcZkCk

    Click the below Image to Enlarge

    ServletInterface Project Dir Structure
    ServletLifeCycle - Example

    ServletsLifeCycle.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    // Extend HttpServlet class
    public class ServletsLifeCycle extends HttpServlet
    {
    
      private static final long serialVersionUID = 1L;
      private int i;
    
      public void init() throws ServletException
      {
        System.out.println("------------------------------------------------------");
        System.out.println(" Init method is called ");
        System.out.println("------------------------------------------------------");
      }
    
      public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                      IOException
      {
        ++i;
        System.out.println(" service method is called "+i+ " time");
        // Set response content type
        response.setContentType("text/html");
    
        // Actual logic goes here.
        PrintWriter out = response.getWriter();
        out.println("<h1>" + " service method is called "+i+ " time" + "</h1>");
      }
    
      public void destroy()
      {
        System.out.println("------------------------------------------------------");
        System.out.println(" destroy method is called ");
        System.out.println("------------------------------------------------------");
      }
    }
    

    web.xml
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"
      metadata-complete="true">
    
        <display-name>ServletsLifeCycle Application</display-name>
        <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
    
         <servlet>
            <servlet-name>ServletsLifeCycle</servlet-name>
            <servlet-class>ServletsLifeCycle</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>ServletsLifeCycle</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
        
    </web-app>
    


    index.html
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>ServletsLifeCycle</title>
    </head>
    <body>
    <p>
    <h3>ServletsLifeCycle</H3>
    <p></p>
    <ul>
    <li><a href="hello">ServletsLifeCycle Test</a></li>
    
    </ul>
    </body></html>
    

    Environment Used

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download HelloworldApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/ServletsLifeCycleApp.zip?attredirects=0&d=1

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Servlets : Webserver

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is a Web Server?

    A Web Server is software (and the underlying hardware) that stores, processes, and delivers web pages to Internet clients—most commonly web browsers. It operates primarily over the HTTP (Hypertext Transfer Protocol) and HTTPS protocols to fulfill client requests across the World Wide Web.

    Whether serving static HTML pages, CSS stylesheets, images, or forwarding dynamic requests to servlet containers, understanding how a web server operates is essential for every web developer.

    How a Web Server Works

    1. Listens on a Port: A web server binds to network ports (standard port 80 for HTTP or 443 for HTTPS) waiting for incoming requests.
    2. Accepts Connection & Parses Request: When a user types a URL or clicks a link, the browser opens a TCP connection and sends an HTTP request specifying the resource path and method (e.g., GET /index.html).
    3. Locates Resource: The web server searches its document root directory for the matching file or evaluates request routing rules.
    4. Sends HTTP Response: If found, the server transmits an HTTP response header (such as 200 OK) along with the content payload. If not found, it returns an error status code like 404 Not Found.

    Popular Web Servers

    • Apache HTTP Server: One of the most mature, flexible, and open-source web servers in computing history.
    • Nginx: High-performance, event-driven web server often used as an HTTP cache and reverse proxy.
    • Microsoft IIS: Enterprise web server integrated tightly with Windows Server environments.

    Recommended Next Watch

    Continue expanding your knowledge of servers and Java web architecture with these tutorials:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=ZY6SO-qeb08

    Click the below Image to Enlarge
    Webserver
    Webserver
    Webserver

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tuesday, 25 March 2014

    Servlets : ServletConfig

    🚀 Master Java Servlets & Enterprise Architecture!

    Subscribe to Ram N Java for clean Java tutorials, servlet configuration guides, and step-by-step code demonstrations!

    🔔 Subscribe to Ram N Java

    What Is ServletConfig in Java Servlets?

    In Java web applications, servlets often need configuration parameters initialized at startup—such as database connection strings, email configurations, or specific file paths. Hardcoding these values directly into the Java class creates rigid code that requires recompilation whenever a parameter changes. The ServletConfig object acts as a bridge between the servlet container and an individual servlet, providing access to servlet-specific initialization parameters defined in the deployment descriptor (web.xml) or annotations.

    Key Concepts & Object Lifecycle

    • One per Servlet: Unlike ServletContext (which is shared across the entire web application), a unique ServletConfig object is created for each individual servlet in the container.
    • Creation During Initialization: The servlet container instantiates ServletConfig during the servlet initialization phase and passes it to the servlet via the init(ServletConfig config) method.
    • Accessing the ServletContext: The ServletConfig object provides a direct reference to the application-wide ServletContext via getServletContext().

    Essential ServletConfig Methods

    The javax.servlet.ServletConfig interface defines four fundamental methods:

    1. getInitParameter(String name): Returns a String containing the value of the named initialization parameter, or null if it does not exist.
    2. getInitParameterNames(): Returns an Enumeration<String> of all initialization parameter names defined for the servlet.
    3. getServletName(): Returns the name of the servlet instance as defined in the deployment descriptor or @WebServlet annotation.
    4. getServletContext(): Returns the reference to the surrounding ServletContext object.

    Why Use ServletConfig?

    • Configurability Without Recompilation: Change servlet startup values in web.xml without touching compiled Java source code.
    • Encapsulation & Scope Isolation: Keeps configuration parameters scoped exclusively to the servlet that requires them, preventing accidental access or collisions across other servlets.
    • Convenient Access: Because GenericServlet implements ServletConfig, methods like getInitParameter() and getServletContext() can be called directly within any servlet subclass.

    Recommended Next Videos

    Deepen your understanding of servlet initialization and container architecture with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=cfwI_bdwQa4

    Click the below Image to Enlarge
    ServletConfig
    ServletConfig
    ServletConfig

    ServletConfig Project Dir Structure
    ServletConfig

    ServletConfigServlet.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ServletConfigServlet extends HttpServlet
    {
    
      private static final long serialVersionUID = 1L;
    
      ServletConfig             servletConfig           = null;
    
      public void init( ServletConfig servletConfig )
      {
        this.servletConfig = servletConfig;
        System.out.println("\n-----------------------------------------------------");
        System.out.println("init method has been called and servlet is initialized");
        System.out.println("-----------------------------------------------------");
    
        System.out.println("Using 'getInitParameter(String name)' method get the value");
        String driverName = servletConfig.getInitParameter("driverName");
        System.out.println("Driver Name : " + driverName);
    
        System.out.println("\nUsing 'getInitParameterNames()'  method get the value");
        Enumeration<String> paramNames = servletConfig.getInitParameterNames();
    
        while( paramNames.hasMoreElements() )
        {
          String paramName = paramNames.nextElement();
    
          String value = servletConfig.getInitParameter(paramName);
    
          System.out.println("paramName : " + paramName + ", Value: " + value);
    
        }
    
      }
    
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                      IOException
      {
    
        System.out.println("\n-----------------------------------------------------");
        System.out.println("doGet method has been called");
        System.out.println("-----------------------------------------------------");
    
        ServletConfig servletConfig = getServletConfig();
        System.out.println("Got servletconfig object using getServletConfig() method : " + servletConfig);
        System.out.println("Servlet Name : " + servletConfig.getServletName());
        System.out.println("ServletContext Object : " + servletConfig.getServletContext());
    
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<html><body>");
        out.print("<b>hello HTTP servlet</b>");
        out.print("</body></html>");
      }
    
      public void destroy()
      {
        System.out.println("-----------------------------------------------------");
        System.out.println("destroy method has been called and servlet is destroyed");
        System.out.println("-----------------------------------------------------");
      }
    
      public ServletConfig getServletConfig()
      {
        return servletConfig;
      }
    }
    

    web.xml
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
      <display-name>ServletConfigServlet</display-name>
      <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
      <servlet>
        <servlet-name>ServletConfigServlet</servlet-name>
        <servlet-class>ServletConfigServlet</servlet-class>
        
         <init-param>  
          <param-name>driverName</param-name>  
          <param-value>oracle.jdbc.driver.OracleDriver</param-value>  
        </init-param>
        
         <init-param>  
          <param-name>username</param-name>  
          <param-value>ram</param-value>  
        </init-param>
        
        <init-param>  
          <param-name>password</param-name>  
          <param-value>ram</param-value>  
        </init-param>   
        
      </servlet>
      
      <servlet-mapping>
        <servlet-name>ServletConfigServlet</servlet-name>
        <url-pattern>/servletConfig</url-pattern>
      </servlet-mapping>
    </web-app>
    

    index.html
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>ServletConfigServlet</title>
    </head>
    <body>
    <p>
    <h3>ServletConfigServlet</H3>
    <p></p>
    <ul>
    
    <li><a href="servletConfig">ServletConfigServlet</a></li>
    
    </ul>
    </body></html>
    

    Environment Used: 

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download ServletConfigApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/ServletConfigApp.zip?attredirects=0&d=1

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Monday, 24 March 2014

    Servlets : HTTPServlet

    🚀 Master Java Servlets & Web Development!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

    👉 Click Here to Subscribe Now

    What is HttpServlet in Java Servlets?

    In Java web development, HttpServlet is an abstract class located in the jakarta.servlet.http (or javax.servlet.http) package that provides an HTTP-specific implementation of the GenericServlet class.

    While the basic Servlet interface and GenericServlet class are protocol-independent, HttpServlet is specially tailored for web applications running over the HTTP protocol. It simplifies handling HTTP requests by providing specialized methods for GET, POST, PUT, DELETE, and other standard HTTP actions.

    The Servlet Inheritance Hierarchy

    Understanding where HttpServlet sits in the hierarchy clarifies how servlets operate under the hood:

    • Servlet (Interface): Declares core lifecycle methods: init(), service(), and destroy().
    • GenericServlet (Abstract Class): Implements Servlet, providing protocol-independent default implementations while leaving service() abstract.
    • HttpServlet (Abstract Class): Extends GenericServlet and overrides the generic service() method to dispatch incoming requests to HTTP-specific handler methods.

    Key Methods of HttpServlet

    When you extend HttpServlet, you typically override one or more of its HTTP verb methods instead of overriding service() directly:

    • doGet(HttpServletRequest req, HttpServletResponse resp): Handles HTTP GET requests (retrieving web pages or fetching search results).
    • doPost(HttpServletRequest req, HttpServletResponse resp): Handles HTTP POST requests (submitting form data, passwords, or file uploads).
    • doPut(HttpServletRequest req, HttpServletResponse resp): Handles HTTP PUT requests (updating existing resources).
    • doDelete(HttpServletRequest req, HttpServletResponse resp): Handles HTTP DELETE requests (deleting resources).
    • doHead(), doOptions(), doTrace(): Support advanced HTTP protocol capabilities.

    Basic HttpServlet Code Example

    Creating a modern servlet by extending HttpServlet and mapping it using the @WebServlet annotation:

    package com.ramnjava.servlets;

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

    @WebServlet("/hello")
    public class HelloHttpServlet extends HttpServlet {

      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h2>Hello from HttpServlet!</h2>");
      }
    }

    Why Do We Almost Always Use HttpServlet?

    • Automatic Method Dispatching: The internal service() method automatically detects the HTTP request method and delegates control to doGet(), doPost(), etc.
    • HTTP Object Support: Provides type-safe access to HttpServletRequest and HttpServletResponse, allowing easy access to cookies, sessions, headers, and query parameters.
    • Industry Standard: Standard enterprise Java web frameworks (such as Spring MVC and Jakarta Faces) build their dispatching engines on top of HttpServlet.

    📺 Related Servlets Architecture Tutorials

    Learn more about servlet internals and request handling from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=JUFBrXOgAlk

    Click the below Image to Enlarge
    HTTPServlet

    HTTPServlet Project Dir Structure

    HTTPServlet

    HelloHttpServlet.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class HelloHttpServlet extends HttpServlet
    {
    
      private static final long serialVersionUID = 1L;
    
      ServletConfig             config           = null;
    
      public void init( ServletConfig config )
      {
        this.config = config;
        System.out.println("-----------------------------------------------------");
        System.out.println("init method has been called and servlet is initialized");
        System.out.println("-----------------------------------------------------");
      }
    
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                      IOException
      {
    
        System.out.println("-----------------------------------------------------");
        System.out.println("doGet method has been called");
        System.out.println("-----------------------------------------------------");
    
        response.setContentType("text/html");
    
        PrintWriter out = response.getWriter();
        out.print("<html><body>");
        out.print("<b>hello HTTP servlet</b>");
        out.print("</body></html>");
      }
    
      public void destroy()
      {
        System.out.println("-----------------------------------------------------");
        System.out.println("destroy method has been called and servlet is destroyed");
        System.out.println("-----------------------------------------------------");
      }
    
    }
    

    web.xml
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
      <display-name>HelloHttpServlet</display-name>
      <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
      <servlet>
        <servlet-name>HelloHttpServlet</servlet-name>
        <servlet-class>HelloHttpServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>HelloHttpServlet</servlet-name>
        <url-pattern>/helloHttpServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    

    index.html
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>HelloHttpServlet</title>
    </head>
    <body>
    <p>
    <h3>HelloHttpServlet</H3>
    <p></p>
    <ul>
    
    <li><a href="helloHttpServlet">HelloHttpServlet</a></li>
    
    </ul>
    </body></html>
    

    Environment Used: 

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download HTTPServletApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/HTTPServletApp.zip?attredirects=0&d=1 

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Sunday, 23 March 2014

    Servlets : GenericServlet

    🚀 Master Java Servlets & Web Development!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

    👉 Click Here to Subscribe Now

    What is GenericServlet in Java?

    In Java Servlet technology, GenericServlet is an abstract class located in the javax.servlet (or jakarta.servlet) package. It defines a generic, protocol-independent servlet by implementing both the Servlet and ServletConfig interfaces, along with Serializable.

    If you implement the raw Servlet interface directly, you are forced to provide implementations for all five of its lifecycle and utility methods (init, service, destroy, getServletConfig, and getServletInfo). GenericServlet simplifies this by providing default boilerplate implementations for all methods except service().

    Where GenericServlet Fits in the Servlet Hierarchy

    • Servlet (Interface): Defines the fundamental contract and lifecycle methods for all servlets.
    • GenericServlet (Abstract Class): Implements Servlet and ServletConfig, making it convenient to write servlets without protocol constraints. The only method left abstract is service().
    • HttpServlet (Abstract Class): Inherits from GenericServlet and specializes in HTTP-specific operations (GET, POST, PUT, DELETE, etc.).

    Key Methods Provided by GenericServlet

    • public abstract void service(ServletRequest req, ServletResponse res): The core request-handling method you must override.
    • public void init(ServletConfig config): Stores the configuration object and calls the convenient no-argument init() method.
    • public void init(): A convenience method designed to be overridden for custom startup initialization without needing to call super.init(config).
    • public void destroy(): Default empty cleanup implementation.
    • getServletContext(), getServletConfig(), getInitParameter(String name): Direct convenience delegate methods.

    GenericServlet Code Example

    Writing a servlet by extending GenericServlet only requires overriding the service() method:

    package com.ramnjava.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.GenericServlet;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebServlet;

    @WebServlet("/genericDemo")
    public class SimpleGenericServlet extends GenericServlet {

      @Override
      public void service(ServletRequest req, ServletResponse res)
          throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println("<h2>Hello from GenericServlet!</h2>");
        out.println("<p>Protocol-independent request processed.</p>");
      }
    }

    GenericServlet vs HttpServlet: What is the Difference?

    • Protocol Dependency: GenericServlet is protocol-neutral (can support protocols other than HTTP), whereas HttpServlet is specifically designed for the HTTP protocol.
    • Request & Response Types: GenericServlet uses generic ServletRequest and ServletResponse; HttpServlet provides specialized HttpServletRequest and HttpServletResponse objects.
    • Method Dispatching: GenericServlet requires you to handle requests directly in service(), while HttpServlet automatically delegates requests to doGet(), doPost(), etc.

    📺 Related Servlets Architecture Tutorials

    Deepen your foundational understanding of Java Servlet architecture with these tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=ieweBKuDVe8

    Click the below Image to Enlarge
    GenericServlet

    GenericServlet Project Dir Structure
    GenericServlet
    HelloGenericServlet.java

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.GenericServlet;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    public class HelloGenericServlet extends GenericServlet
    {
    
      private static final long serialVersionUID = 1L;
    
      ServletConfig             config           = null;
    
      public void init( ServletConfig config )
      {
        this.config = config;
        System.out.println("-----------------------------------------------------");
        System.out.println("init method has been called and servlet is initialized");
        System.out.println("-----------------------------------------------------");
      }
    
      public void service( ServletRequest req, ServletResponse res ) throws IOException, ServletException
      {
        System.out.println("-----------------------------------------------------");
        System.out.println("service method has been called");
        System.out.println("-----------------------------------------------------");
    
        res.setContentType("text/html");  
          
        PrintWriter out=res.getWriter();  
        out.print("<html><body>");  
        out.print("<b>hello generic servlet</b>");  
        out.print("</body></html>");  
    
      }
    
      public void destroy()
      {
        System.out.println("-----------------------------------------------------");
        System.out.println("destroy method has been called and servlet is destroyed");
        System.out.println("-----------------------------------------------------");
      }
    
    }
    

    web.xml

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
      <display-name>HelloGenericServlet</display-name>
      <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
      <servlet>
        <servlet-name>HelloGenericServlet</servlet-name>
        <servlet-class>HelloGenericServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>HelloGenericServlet</servlet-name>
        <url-pattern>/helloGenericServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    

    index.html

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>HelloGenericServlet</title>
    </head>
    <body>
    <p>
    <h3>HelloGenericServlet</H3>
    <p></p>
    <ul>
    
    <li><a href="helloGenericServlet">HelloGenericServlet</a></li>
    
    </ul>
    </body></html>
    

    Environment Used: 

    JDK version :1.6.0_30
    Tomcat version : 7.0.50

    To Download GenericServletApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/GenericServletApp.zip?attredirects=0&d=1 

     See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Newer Posts Older Posts Home

    Tutorials