postheadericon Difference between GenericServlet and HttpServlet

GenericServlet:


  • As name says it Generic in nature. Means GenericServlet is protocol-independent.
  • import  javax.servlet.servlet package
  • super class of GenericServlet are java.lang.Object and it implements three interfaces Servlet, ServletConfig and java.io.Serializable
  • To write a generic servlet, override the abstract service().
  • GenericServlet  lifecycle methods use ServletConfig interface.
  • GenericServlet implements the log() from ServletContext interface.
  • Prototype:
    • public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • Example:




import javax.servlet.*;
import java.io.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(
  name="WTAD",
  urlPatterns={"/index.html","/BipinRupadiya.blogspot.com"}
)
public class GenricServletDemo extends GenericServlet
{
 public void service(ServletRequest request, ServletResponse response)
  throws ServletException,IOException
 {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<HTML><HEAD><TITLE>WTAD</TITLE></HEAD> <body>");
  String str="<h1>welcome to </h1>";
  str=str+"<br>www.bipinrupadiya.blogspot.com";
  out.println(str);
          out.println("</body> </html>");
 }
}



HttpServlet:


  • As name says it is http protocol specific.
  • Import javax.servlet.http package
  • Supper class of HttpServlet is GenericServlet and it implements java.io.Serializable interface
  • HttpServlet have all the properties of GenericServlet because it extends GenericServlet class
  • To write HttpServlet we have to override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy(), getServletInfo()
  • Prototype:
    • public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
  • Example:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import javax.servlet.annotation.WebServlet;
@WebServlet(
  name="WTAD",
  urlPatterns={"/index.html","/BipinRupadiya.blogspot.com"}
)

public class ServletDemo extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException,IOException
 {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<HTML><HEAD><TITLE>WTAD</TITLE></HEAD> <body>");
  String str="<h1>welcome to </h1>";
  str=str+"<br>www.bipinrupadiya.blogspot.com";
  out.println(str);
  out.println("</body> </html>");
 }
}



0 comments: