HttpServlet class in Servlet

In Servlet API, the HttpServlet class is an abstract class extending from GenericServlet class. The GenericServlet class is also an abstract class that implements the Servlet interface. Therefore the Servlet interface is the center abstraction in servlet API, and either directly or indirectly every servlet component is implementing the Servlet interface.

The Servlet API contains four packages. The package name upto Java EE,

  • javax.servlet
  • javax.servlet.http
  • javax.servlet.annotation
  • javax.servlet.descriptor

After changing JEE name from Java EE to Jakarta EE (see 123) the package name “javax” is also changed to “jakarta”. Therefore the current packages names are,

  • jakarta.servlet
  • jakarta.servlet.http
  • jakarta.servlet.annotation
  • jakarta.servlet.descriptor

The three most important resources of Servlet API are:-

  • jakarta.servlet.Servlet (I)
  • jakarta.servlet.GenericServlet (AC)
  • jakarta.servlet.http.HttpServlet (AC)

The HttpServlet abstract class belongs to the jakarta.servlet.http package. Most of the servlet components are developed to support HTTP features which makes HttpServlet class one of the most important classes in Servlet API. The HttpServlet class supports HTTP and HTTPS protocols, and it contains methods to handle different modes/methods of requests.

Java Servlet API important Resources

Note that the HttpServlet class is an abstract class but it doesn’t contain any abstract method. In Java, an abstract class can contain only abstract methods or only concrete methods or both abstract and concrete methods.  HttpServlet is an example of an abstract class that contains only concrete methods i.e. no abstract method. 


Service(-,-) Method in HttpServlet class

HttpServlet class of Servlet API contains 2 service(-,-) methods. Among them, one service(-,-) method is an implementation of superclass GenericServlet (AC), and the other service(-,-) method is directly defined in the HttpServlet class itself. We can differentiate them through accessibility modifiers and parameters.

  • public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException:- It is a public method and implemented from superclass GenericServlet. This method doesn’t support HTTP features.
  • protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException:- It is a protected method directly defined in HttpServlet class, and it supports HTTP features.

HttpServlet Class Methods to Handle Different HTTP Request Methods

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. The HTTP methods/modes are:- 

  • GET 
  • POST 
  • PUT 
  • DELETE 
  • OPTIONS 
  • TRACE 
  • HEAD.

The HttpServlet class contains several methods to support these request methods/modes, and those methods commonly referred to as doXxx(-) methods where Xxx is HTTP mode/method. The 7 doXxx(-,-) methods given in HttpServlet (AC) of Servlet API are:- 

  • doGet(-,-) 
  • doPost(-,-) 
  • doPut(-,-) 
  • doDelete(-,-) 
  • doOptions(-,-) 
  • doHead(-,-) 
  • doTrace(-,-) 

The signature of these 7 doXxx(-,-) methods are:-
protected void doXxx(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException.

HttpServlet MethodUsed to handle HTTP request
doGet(-,-)GET 
doPost(-,-) POST
doPut(-,-) PUT 
doDelete(-,-) DELETE 
doOptions(-,-) OPTIONS 
doHead(-,-) HEAD 
doTrace(-,-) TRACE 

Different types of clients (browser, FTP client, and e.t.c.) can give 7 modes of request to the web application but as a browser, it can give only two modes of request:- GET and POST. Even though these 7 modes of request are there, the browser support only GET and POST mode requests therefore while developing web applications for end-users who operate websites using browsers, we need to work with only doGet(-,) and doPost(-,-) methods.

The FTP client uses the remaining modes/methods of requests. The FTP clients are useful to host the web application, to keep web applications on the internet, maintenance of the web application, remove web components from the hosted web application and e.t.c. While keeping web applications to the internet and adding new components in the web application PUT mode request is used. Similarly to remove existing web components or web application DELETE mode is used.

While learning Servlet, JSP we will always use only doGet(-,-) and doPost(-,-) methods for the GET and POST mode requests. All the remaining modes and methods will be used in the WebServices, RestFul WebServices, where we work with all 7 modes of request.

Limitation of service method in Servlet

The service(-, -) method is capable of processing both GET and POST mode/method requests given by the client, but it is having the following limitations,

  1. There are two service methods given in HttpServlet class, where service(HttpServletRequest req, HttpServletResponse res) can work with HTTP features, and service(ServletRequest req, ServletResponse res) method can’t work with HTTP feature.
  2. The service method doesn’t provide any environment to write separate request processing logic for the GET, POST modes of request because it is a single method. The GET and POST mode requests can’t be differentiated simply through conditional (if-else, switch-case) statements.
  3. Basically, the service method is not designed based on protocol HTTP standards to process 7 ways/modes of request:- GET, POST, PUT, DELETE, OPTIONS, TRACE, and HEAD.
  4. HttpServlet class contains two service methods, and it is confusing the developers

To solve all these problems we should use the doGet and doPost method in our servlet component, and it is the standard approach used in web application development. In doGet(-,-) and doPost(-,-) in the servlet tutorial, we will discuss how we should write the logic for the GET and POST mode requests.

Advantages of Working with doXxx(-,-) Methods

  • The doXxx(-,-) methods are given to process the 7 modes of requests from client applications.
  • These methods are designed based on protocol HTTP standards.
  • It gives HttpServletRequest, HttpServletResponse as parameters to work with protocol HTTP features.
  • We can write separate request processing logics for the GET and POST methods of request.
  • Writing request processing logic in doXxx(-,-) method is industry standard, compared to the service(-,-) method.

Developing a servlet component having service(-,-) method to process the request is not good practice because as a single method it can’t differentiate logics for “GET” and “POST” mode requests. We can’t write different logic for both GET and POST mode requests in a single service(-,-) method. Due to this reason working with the service(-,-) method is not a standard approach while developing servlet components.

Place doXxx(-) methods in the servlet component having request processing logic. Since we can place multiple doXxx(-) methods at a time in a servlet component, we can differentiate logics for different modes of requests.

Conclusion:- Stop using the service(-,-) method to place request processing logic in servlet components because it can’t differentiate logics for “GET” and “POST” requests. 

Methods of HttpServlet class

The different methods of this class are:-

  • public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
  • protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doOptions(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doHead(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected void doTrace(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  • protected long getLastModified(HttpServletRequest req):- It returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT.

The all doXxx(-,-) method of HttpServlet class have logic to send 405 error response to browser window.

How to Override these Methods in our Servlet Component

While overriding superclass methods in subclass we can use either the same modifier or strong modifier. But it is recommended to take the strong modifier for more visibility.

While overriding the protected methods of superclass we can use the same protected modifier or strong public modifier in the subclass. Strong modifier “public” is recommended for more visibility.

Accessibility modifier order for visibility:- private < default < protected < public.

All the protected methods of HttpServlet can be overridden in our servlet component class either with the same protected modifier or with a strong public modifier (recommended). Since there is a possibility of overriding protected methods of HttpServlet class having “public” modifiers in our servlet components. So, it is always recommended to override them with the public modifier.

Below is an example that is not recommended to use in our servlet component class,

// not recommended approach
public class ServletComponent extends HttpServlet {
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

      // request processing logic
   }
}

This is an example which is recommended to use in our servlet component class,

// recommended approach
public class ServletComponent extends HttpServlet {
   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {

      // request processing logic
   }
}

How doXxx(-,-) Method is called by the Servlet Container

A servlet container is calling only init(), service(), and destroy() methods as a cycle life cycle, then how doXxx() methods are executed? In the servlet life cycle, we will see more about life cycle methods. The servlet container directly won’t call doXxx(-,-) methods. It only calls the service(ServletRequest req, ServletResponse res) method for every request given from the browser. 

Sample of HttpServlet class in Servlet API,

// HttpServlet.java (Pre-defined class)
public abstract class HttpServlet extends GenericServlet implements Serializable {

   // 1st service method
   public void service(ServletRequest req, ServletResponse res) 
         throws ServletException, IOException {
      // Type casting 
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      // Calling 2nd service method
      service(request, response);
   }

   // 2nd service method
   protected void service(HttpServletRequest req, HttpServletResponse res) 
         throws ServletException, IOException {
      // fetch request method
      String method = req.getMethod();
      // call approriate doXxx(-,-) method
      if(method.equals("GET"))
         doGet(req, res);
      else if(method.equals("POST"))
         doPost(req, res);
      else if(method.equals("HEAD"))
         doHead(req, res);
      else if(method.equals("DELETE"))
         doDelete(req, res);
      else if(method.equals("PUT"))
         doPut(req, res);
      else if(method.equals("OPTIONS"))
         doOptions(req, res);
      else if(method.equals("TRACE"))
         doTrace(req, res);
      else
         res.sendError("Invalid request method");
   }

   // doGet(-,-) method
   protected void doGet(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {
      // send 405 error response to browser window
   }

   // doPost(-,-) method
   protected void doPost(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {
      // send 405 error response to browser window
   }

   // remaining other doXxx(-,-) are also there, 
   // we are not highlighting them
   protected void doXxx(HttpServletRequest req, HttpServletResponse res)
         throws ServletException, IOException {
      // send 405 error response to browser window
   }
}

The .class file for HttpServlet class is available in <Tomcat_home>\lib\servlet-api.jar\jakarta\servlet\http, you can use any online Java decompiler to convert .class file to .java file or see here the source code of HttpServlet.java file.

The all doXxx(-,-) method of HttpServlet class has logic to send 405 error responses to the browser window. Therefore if we don’t override them in our servlet class and service method called them then we will get 405 error.

In the execution of the Servlet Component don’t let the control going to doXxx(-,-) methods of javax.servlet.http.HttpServlet class because they always generate a 405 error response page indicating our servlet class is totally incomplete to process the request.

Whenever our servlet component extends from HttpServlet class then the servlet container perform the following operation,

  • Servlet containers call the public service(ServletRequest req, ServletResponse res) method as a life cycle method for every request given from the browser.
  • If the servlet component overrides this method then it will be executed from the servlet component. Else this method will be executed from HttpServlet class.
  • The public service(ServletRequest req, ServletResponse res) method of HttpServlet class internally calls protected void service(HttpServletRequest req, HttpServletResponse res).
  • If our servlet component overrides this method then it will be executed from the servlet component else it will be executed from the HttpServlet class.
  • The protected service(ServletRequest req, ServletResponse res) method of HttpServlet class internally calls doXxx(-,-) method for different request modes/methods. For example, if it is a GET method request then it will internally call the doGet(-,-) method, and similarly for the POST method request internally doPost(-,-) method will be called. 

Example-1

If our servlet component contains both service(-,-) and doXxx(-,-) methods then the service(-,-) method will be executed from our servlet component class, not from the HttpServlet class. Therefore the service(-,-) method of HttpServlet class never gets a chance to execute. The service(-,-) method of our servlet component class contains its own request processing logic, finally doXxx(-,-) method also will never get a chance to execute.

package com.kp.servlet;

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

public class CheckVoterServlet extends HttpServlet {

   @Override
   public void service(ServletRequest req, ServletResponse res) 
               throws ServletException, IOException {
      PrintWriter pw = res.getWriter();
      pw.println("1st service method executed.");
   }

   @Override
   public void service(HttpServletRequest req, HttpServletResponse res) 
               throws ServletException, IOException {
      PrintWriter pw = res.getWriter();
      pw.println("2nd service method (which support HTTP) executed.");
   }

   @Override
   public void doPost(HttpServletRequest req, HttpServletResponse res) 
               throws ServletException, IOException {
      PrintWriter pw = res.getWriter();
      pw.println("doPost method executed.");
   }

   @Override
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
               throws ServletException, IOException {
      PrintWriter pw = res.getWriter();
      pw.println("doGet method executed.");
   }
}

In the above servlet component, second service(-,-), doGet(-,-) and doPost(-,-) method will never execute. If we remove the first service(-,-) method then also doGet(-,-) and doPost(-,-) method will never execute.

Web browsers support only GET and POST mode requests. By default, every request sent by our browser is a GET method request, and for POST method requests you can use the HTML form component with method= “POST”. You can understand it better after learning HTML to servlet communication using the form.

Conclusion:- Don’t use both service(-,-)  and doXxx(-,-) method in your servlet component. Either use service(-,-) method (which is not recommended), or use doXxx(-,-) method (recommended) for request processing logic.

Example-2

public class TestServlet extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
         throws ServletException, IOException {
      // Some logic
   }
}

With respect to the above code

  • The end-user gives the request to this servlet component having the request method “GET” from the client (browser window).
  • Servlet Container creates or locates this Servlet Class object, completes the instantiation and initialization-related life cycle operations.
  • Servlet Container raises request processing event and calls public service(ServletRequest, ServletResponse) method on this servlet Class object as life cycle method. Since this service(-,-) method is not available in this Servlet component, therefore superclass (pre-defined HttpServlet Class) public service(-,-) method executes.
  • The public service(ServletRequest, ServletResponse) method of pre-defined HttpServlet class converts simple ServletRequest object to HttpServletRequest object, simple ServletResponse object to HttpServletResponse object. After that, it calls the protected service(HttpServletRequest, HttpServletResponse) method (2nd service method). Since this service(-,-) method is not available in our TestServlet class so it will be executed from the superclass (pre-defined HttpServlet class).
  • The protected service(-,-) method (2nd service method) of pre-defined HttpServlet Class reads request method of client-generated request and calls an appropriate doXxx(-,-) method i.e. doGet(-,-) method in this case because by default generated request method is “GET”. Since the doGet(-,-) method is available in the current Servlet Component so, that method will be executed from TestServlet.
  • The doGet(-,-) method of the TestServlet component will process the request and sends generated response to the browser window as a web page.

FAQ on HttpServlet Class

Q) If both service(-,-) methods are placed in our Servlet Component then which method will be executed?
Ans:- Since public service(ServletRequest req, ServletResponse res) is a life cycle method because it is called by the servlet container so only this service method will be executed.

Q) What is the best way to write request processing logic?
Ans:- The best practice is to override both doPost(-,-) and doGet(-,-) methods in your servlet class and keep the request processing logic in one of those methods and call that method from another method.

Q) When all the methods of the pre-defined HttpServlet class are concrete methods then why the class itself is given as an abstract class?
Ans:- The javax.servlet.http.HttpServlet class is an abstract class, even though none of the methods within it are abstract methods. It contains seven doXxx(-,-) methods to match seven ways of making HTTP requests. (GET / POST / DELETE / OPTIONS / TRACE / PUT / HEAD). These methods are the request processing methods of a HttpServlet class, just like the service(-,-) method for a GenericServlet.

Since there is only one request-processing method in GenericServlet, it is defined as abstract in javax.servlet.GenericServlet class, which makes the developers making his class to extend javax.servlet.GenericServlet class, to provide the implementation only for one method, but in the case of javax.servlet.http.HttpServlet class if all 9 (2 service and 7 doXxx ) request-processing methods are defined as abstract, then every developer who creates a child class for it, has to provide implementations for all the 9 methods, which is quite an issue. So, the specification has made javax.servlet.http.HttpServlet class to contain implementations for all the 9 methods, but they made the javax.servlet.http.HttpServlet class itself as abstract, which means no Developer/ServletContainer can create an instance of it directly.

By giving HttpServlet class as an abstract class they are killing the possibilities of configuring HttpServlet class itself as a servlet component in web.xml because servlet container can’t instantiate any abstract class.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.