1. We can create servlet by implementing Servlet interface directly.
  2. In this case we should provide implementation for all 5 methods of Servlet interface.
  3. This makes code unnecessary complected.We can resolve this problem by using GenericServlet


  1. GenericServlet implements Servlet interface and provides implementation for all it’s method except service() method hence it is abstract.
  2. Developing Servlet by extending GenericServlet is very easy because we have to provide implementation only for service() method.
  3. GenericServlet makes programers life very simple because programmer has to concentrate only on service() method instead of all methods.

Creating servlet by extending GenericServlet

  1. Create a class that extends GenericServlet
  2. package com.java2learn;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.GenericServlet;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class GenericServletDemo extends GenericServlet {
    	public void service(ServletRequest request, ServletResponse response)
    			throws ServletException, IOException {
    		PrintWriter out=response.getWriter();
    		out.println("<h1>Welcome to GenericServlet.</h1>");
  3. Configure the above servlet in web.xml as follows.
  4. <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	id="WebApp_ID" version="2.5">
  5. Final structure of the project
  6. GenericServlet

  7. Create the war file and deploy in the webapps folder of tomcat.
  8. C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps

  9. Accessing servlet from web application .Open the browser and type the following URL in the address bar
  10. http://localhost:9091/WebApp/genericServlet

  11. Output
  12. Output

Download project: