Class HttpServlet

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. The javax.servlet.http.HttpServlet class is a slightly more advanced base class than the GenericServlet.

The HttpServlet class reads the HTTP request, and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.

Similar to the GenericServlet class this class is also abstract and we extend it make the SubClass work like a servlet. The SubClass must override one of the following methods:-

Popular Tutorials


service() method of HTTPServlet class is not abstract as was the case in the GenericServlet class and there is hardly any need to override that method as by default it contains the capability of deciding the type of the HTTP request it receives and based on that it calls the specific method to do the needful. For example, if an HTTP GET request calls the servlet then the service nethod of the HTTPServlet class determines the request type (it'll find it to be GET) and subsequently calls doGet() method to serve the request.



Methods of HttpServlet class



To respond to e.g. HTTP GET requests only, you will extend the HttpServlet class, and override the doGet() method only. Here is an example:
public class SimpleHttpServlet extends HttpServlet {

  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {

      response.getWriter().write("<html><body>GET response</body></html>");
  }
}
If you want to handle both GET and POST request from a given servlet, you can override both methods, and have one call the other. Here is how:
public class SimpleHttpServlet extends HttpServlet {

  protected void doGet( HttpServletRequest request,
                        HttpServletResponse response)
        throws ServletException, IOException {

      doPost(request, response);
  }

  protected void doPost( HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException {

      response.getWriter().write("GET/POST response");
    }
}

I would recommend you to use the HttpServlet instead of the GenericServlet whenever possible. HttpServlet is easier to work with, and has more convenience methods than GenericServlet.

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

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

Labels: