Two service methods in HttpServlet class
Whenever we write a servlet, we inherit our class from HttpServlet which contains two service methods. Let’s have a look at the difference between both.
This article assumes that you have a basic knowledge of method overriding and overloading.
If you don’t, GET A LIFE!
So, getting on with the article.
which in turn inherits from GenericServlet class
So, the hierarchy becomes
Our MyServlet inherits HttpServlet which inherits GenericServlet.
For now, just keep that in mind and we will get back to it.
Overview of the methods
Now, HttpServlet is an Abstract class and its all methods are concrete.
HttpServlet is derived from GenericServlet which is also an abstract class.
HttpServlet has two service methods.
One public and one protected.
The public method is inherited from the GenericServlet class.
HttpServlet extends GenericServlet, remember ?
The public method has two parameters; ServletRequest and ServletResponse.
public void <b>service</b>(ServletRequest req,
The protected method overloads the public method and it also has two parameters; HttpServletRequest and HttpServletResponse.
protected void <b>service</b>(HttpServletRequest req,
This is an excellent example of Dynamic Polymorphism (overriding) and Static Polymorphism (overloading).
How the container works with them
The typical call to a servlet is:
The container calls the public service method(the one inherited from GenericServlet)
The service method internally typecasts the ServletRequest to HttpServletRequest and ServletResponse to HttpServletResponse.
The protected service method then internally verifies if it is GET or POST and promptly calls doGet() or doPost().
Not getting it ?
Have a look at it this way
Container receives request and calls the public service method which in turn calls the protected service method. Now, if the method is get, it calls the doGet and if it is post, it calls the doPost.
Now, the question may arise in mind
Why doesn’t the public service method do the job that the protected method is doing?
The answer is, separation of concerns. Generic method or public method handles the generic functionality and the protected method is an HTTP-specific version of the public method. It handles the HTTP-specific functionality.
Help by sharing!!