Difference between GenericServlet and HttpServlet

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementaion of all the methods of these interfaces except the service method. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.


Popular Tutorials

Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:


Difference between HttpServlet and GenericServlet-
javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable

javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
Servlet Example by inheriting the GenericServlet class-

Let's see the simple example of servlet by inheriting the GenericServlet class.
import java.io.*;  
    import javax.servlet.*;  
      
    public class HelloServlet extends GenericServlet{  
    public void service(ServletRequest req,ServletResponse res)  
    throws IOException,ServletException{  
      
    res.setContentType("text/html");  
      
    PrintWriter out=res.getWriter();  
    out.print("<html><body>");  
    out.print("<b>hello generic servlet</b>");  
    out.print("</body></html>");  
      
    }  
    }  



<<Previous <<   || Index ||   >>Next >>


Servlet Related Posts
  1. Java Servlets Overview
  2. Servlet Life Cycle
  3. Servlet Example
  4. Difference between ServletConfig and ServletContext
  5. What is web application?
  6. Advantages of Servlets over CGI
  7. GenericServlet Example
  8. RequestDispatcher Example
  9. ServletConfig
  10. ServletContext
  11. Servlet Filter Example
  12. Database Access Example using Sevlet
  13. File Uploading Example using Servlet

Labels: