Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid reason for servlet to override HttpServlet service method

Tags:

java

servlets

dry

I have a few legacy Servlets overriding service method,

According to HttpServlet docs service method shouldn't be overridden, only in specific cases:

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

I found several answer about service method that calls the do methods

the calls to doGet(), doPost() and the other do-methods are in the HttpServlet class

It's done by default and can be overriden

Since your servlet overrides the service() method and provides a different implementation, it doesn't do that anymore. Instead, it does... what the code in the method does.

and answers that says why not overide it

let servlet handle other methods.

But I didn't any valid reason why to override this method, is there any case(s) ?

It seems that it may correspond to DRY (Don't repeat yourself) rule, so all do methods will execute same method.

like image 774
user7294900 Avatar asked Sep 25 '18 06:09

user7294900


People also ask

Can we override service method in servlet?

Unlike Generic Servlet, the HTTP Servlet doesn't override the service() method. Instead it overrides the doGet() method or doPost() method or both. The doGet() method is used for getting the information from server while the doPost() method is used for sending information to the server.

Which of the following methods belong to HttpServlet class?

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

What is HttpServlet in servlet?

An HTTP servlet is a special type of servlet that handles an HTTP request and provides an HTTP response, usually in the form of an HTML page.


1 Answers

You'd have to override service if you need to handle a non-standard HTTP method, i.e. one that hasn't been dispatched to a doXxx method by HttpServlet.

As the RFC 2616 HTTP documentation says:

The set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for separately extended clients and servers.

Your own quote even says the same, although only implicitly:

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

Implicit is that non-standard requests must be handled by overriding the method.

like image 189
Andreas Avatar answered Oct 19 '22 23:10

Andreas