Ori Marko
Ori Marko

Reputation: 58822

Valid reason for servlet to override HttpServlet service method

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.

Upvotes: 5

Views: 478

Answers (1)

Andreas
Andreas

Reputation: 159135

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.

Upvotes: 5

Related Questions