sharath
sharath

Reputation: 123

protected service(ServletRequest, ServletResponce) vs public service(HTTPServletRequest, HTTPServletResponce)

I've tried looking for the differences between the two. I found the code, where the public service method is in turn calling protected service method by passing HttpServletRequest and HttpServletResponse objects to it. But Why is an extra protected service method added in HttpServlet class? Is there any use? what happens if it is not there?

Upvotes: 0

Views: 430

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34796

I think JavaDoc explains it all:

/**
 * Dispatches client requests to the protected
 * <code>service</code> method. There's no need to
 * override this method.
 * ...
 */
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException

and

/**
 * Receives standard HTTP requests from the public
 * <code>service</code> method and dispatches
 * them to the <code>do</code><i>XXX</i> methods defined in 
 * this class. This method is an HTTP-specific version of the 
 * {@link javax.servlet.Servlet#service} method. There's no
 * need to override this method.
 */
protected void service(HttpServletRequest req, HttpServletResponse resp)

Basically the public version of the method does some checking whether the ServletRequest and ServletResponse parameters are actually instances of HttpServletRequest and HttpServletResponse respectively, casts them and passes them to the protected method containing logic specific to handling HTTP requests.

So if you wanted to just override the logic that deals with the HTTP request processing you would override the protected method. Although as stated in the JavaDoc that shouldn't be really necessary, but it could probably be needed in some specific scenario.

Upvotes: 1

Related Questions