HttpServlet class in Servlet

As of now, we have discussed what is GenericServlet. In this article, we will discuss what is HttpServlet.In order to create a servlet, we have first seen by implementing ServletInterface Interface, then we saw By extending GenericServlet class. Now we will see by extending HttpServlet class.

What is HttpServlet?

HttpServlet is a class that extends the GenericServlet and Serializable interface. It provides the framework for handling the HTTP based protocol request. As we know, in GenericServlet, we need to override the service() method but in the case of HttpServlet we don’t need to do that instead it overrides specific methods like doGet(),doPost(), etc based on the request.

How HttpServlet Works?

  • The client(web browser) requests the server.
  • These requests can be of any type like- GET, POST, etc. Now Web Server will dispatch these requests to the service() method for handling the request.
  • Now service() will see if it is a GET request it will dispatch to doGet()  method or if it is a POST request it will dispatch to doPost() and likewise.

Advantages of HttpServlet class

  • It is convenient to use HttpServlet over GenericServlet.
  • If a programmer uses HttpServlet, he can use the functionalities of both the classes (itself & GenericServlet).

Disadvantages of HttpServlet class

  • It is protocol dependent.

Methods in HttpServlet class

  • public void service(ServletRequest req, ServletResponse res): This method dispatches the request to any HTTP type.
    • Parameters:
      • req: request from the client.
      • res: response to the client.
  • protected void service(HttpServletRequest req, HttpServletResponse res):This is the HTTP version of the service() method which accepts HTTP specific request.
  • protected void doGet(HttpServletRequest req, HttpServletResponse res):This method handle the GET request.It is used to get information from the server.
  • protected void doPost(HttpServletRequest req, HttpServletResponse res):This method handle the POST request.It is used for sending information to the server.
  • protected void doHead(HttpServletRequest req, HttpServletResponse res):This method handles the HEAD requests.It is used to send header information with no entity-body.
  • protected void doOptions(HttpServletRequest req, HttpServletResponse res): This method handles the option request.
  • protected void doPut(HttpServletRequest req, HttpServletResponse res): This method handles the PUT request.It allows a client to store information on the server.
  • protected void doTrace(HttpServletRequest req, HttpServletResponse res): This method handles the TRACE request.A TRACE returns the headers sent with the TRACE request to the client so that they can be used for debugging.
  • protected void doDelete(HttpServletRequest req, HttpServletResponse res): This method handles the DELETE request.It allows the client to delete information from the server.
  • protected long getLastModified(HttpServletRequest req): This method return the time when the request was last modified.

Let’s see the Example for HttpServlet

In this example, We have created our Servlet(HttpServletExample.java) which extends HttpServlet class. Create an index.html file inside WebContent/index.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome to Codedec...!!!!</title>
</head>
<body>
  <form action="Myservlet">
    Enter number 1:<input type="text" name="num1"> Enter number 2:<input
      type="text" name="num2"> <input type="submit" value="Submit"
      id="button-1" />
  </form>
</body>
</html>

Now we have a web.xml file (it is a deployment descriptor file). We will see the explanation ahead in the tutorial.

<?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"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  id="WebApp_ID" version="3.0">
  <display-name>HttpServletDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>HttpServletEx</servlet-name>
    <servlet-class>HttpServletExample</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HttpServletEx</servlet-name>
    <url-pattern>/Myservlet</url-pattern>
  </servlet-mapping>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/HttpServletExample")
public class HttpServletExample extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at:
    // ").append(request.getContextPath());
    System.out.println("in get");
    PrintWriter out = response.getWriter();
    int number1 = Integer.parseInt(request.getParameter("num1"));
    int number2 = Integer.parseInt(request.getParameter("num2"));
    int number3 = number1 * number2;
    out.println("<html><body>");
    out.println("Servlet by extending HttpServlet.....");
    out.println("<p> Result is: " + number3 + "</p>");
    out.println("</body></html>");
  }
}

Difference between GenericServlet & HttpServlet class

GenericServlet

HttpServlet

A class that implements Servlet, ServletConfig, and Serializable Interface. A class that extends the GenericServlet class and implements the Serializable interface.
Protocol Independent. Protocol dependent.
Immediate subclass of ServletInterface. Immediate subclass of GenericServlet.
Defined in javax.servlet package. Defined in javax.servlet.http package.
service() method is abstract here. service() method is not abstract here.
Not used commonly It is used more often.

Thus we have seen the classes used in Servlet. In the next article, we will look at the Interfaces used in Servlet.