Saturday, 20 September 2014

GenericServlet vs HttpServlet

You have seen in servlet tutorial here, I have given idea about Servlet APIs, Servlet interface implemented by GenericServlet Class and GenericServlet class extended by HttpServlet. So, why HttpServlet if GenericServlet? What is the advantage you will achieve by HttpServlet?
Let us know about more about GenericServlet and HttpServlet-

GenericServlet- This is Generic class and used to create protocol independent Servlet. When you create servlet class, need to ovverride service() method. service() method has two parameter ServletRequest and ServletResponse. These parameter is also Generic and used to pass protocol independent parameter. This means it can handle any type of request e.g. http, ftp, smtp.

Example is given in previous chapter, to go click here,

HttpServlet- This class is extended from GenericServlet. This is specific to Http protocol which used to create http protocol dependent Servlet. When you create servlet class, you have choices to ovverride either service(), doGet() or doPost()  method. doGet() and doPost() method has two parameter HttpServletRequest and HttpServletResponse. These parameter is specific to http and used to pass http protocol dependent parameter. This servlet class is introduced to make life easier, so that developer no need to worry about http protocol things separately.

E.g.

package example; 
import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class MyServlet extends HttpServlet{ 
 
 //this will handle http get
  public void doGet(HttpServletRequest req,HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();

    out.println("Basic http servlet example");
    out.close();
  }
 
//this will handle http post 
  public void doPost(HttpServletRequest req,HttpServletResponse res)
    throws ServletException, IOException
  {
   doGet(req,res);
  } 
}
 
 
To go next chapter click here 

No comments:

Post a Comment