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
  • No comments:

    Post a Comment

    Tutorials