GenericServlet Class Example

In this example, we will see how to use GenericServlet class with an example. GenericServlet class defines a generic, protocol-independent servlet. It means GenericServlet class can handle any type of request so it is protocol-independent.

GenericServlet Class Diagram

The below diagram shows that the GenericServlet class implements the Servlet and ServletConfig interfaces.

GenericServlet Class Example

Let's demonstrate the usage of GenericServlet class with an example.

Step 1: Add servlet dependency to pom.xml

Let's first add servlet 4.0.1 dependency to our pom.xml:
    <name>java-servlet-tutorial Maven Webapp</name>
        <!-- -->

Step 2: Create HelloWorldServlet which extends GenericServlet

Let's see the simple example of the servlet by inheriting the GenericServlet class. Note that we are using getServletName() and getInitParameter() methods within this example.
package net.javaguides.servlet.tutorial.genericservlet;


import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(name = "HelloWorld", initParams = {
    @WebInitParam(name = "username", value = "Ramesh"),
    @WebInitParam(name = "password", value = "Pass@123")
}, urlPatterns = "/hello")
public class HelloWorldServlet extends GenericServlet {

    private static final long serialVersionUID = 1 L;

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        PrintWriter printWriter = res.getWriter();
        printWriter.print("<h1>Hello World GenericServlet Class Example</h1>");
        printWriter.print("<p> Servlet name :: " + getServletName() + "</p>");
            .print("<p> Servlet username init parameter :: " + getInitParameter("username") + "</p>");
            .print("<p> Servlet password init parameter :: " + getInitParameter("password") + "</p>");
        printWriter.print("<a href=\"\">Java Guides</a>");
Note that we are using @WebServlet annotation to create Servlet component.

Step 3: Demo

Let's deploy above servlet into a servlet container, for example, Tomcat 8. Once tomcat server is up and running without any errors then hit http://localhost:8080/java-servlet-tutorial/hello URL in a browser. You can see below web page on the browser:

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course