• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

service () vs doPost ()

 
John Davis
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the pros and or cons associated with using the service method versus the doPost and doGet methods.
 
Kevin Mukhar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generally, you should leave service() alone, and just override the doXXX method that you want to support. When most developers override service(), they don't do anything more than is already provided by the base class. If you are not going to extend the functionality already provided by the base class, then your just uneccessarily duplicating code, and there's no reason to override service().
The other reason generally given to this question is that the service() method provided in the base class handles housekeeping chores for you which you would need to provide yourself if you override service().
The obvious chore service() performs is to decide whether to call doPost() or DoGet(). The other things it does is decide whether to call other methods like doHead(), doDelete(), doOptions(), doPut(), doTrace(), etc. You see, there are a lot of methods that your servlet inherits from the base classes, all of which are valid HTTP requests. Most developer's only implement doPost() or doGet(), but service must be able to handle all the doXXX methods. Using the base class service method allows all those doXXX methods to be supported automatically.
If you wanted to override service() correctly, you would need to provide code that handled all those HTTP requests. Sure, all you need is to determine which request is being made, and then call the appropriate method in the base class. However, why bother when that's already provided by the base class service() method.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13073
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no particular reason to write your own service method as long as you are working with standard HTTP protocol messages. The service method simply looks at the request "method" ("GET" "POST" etc.) and calls doGet, doPost etc etc. according to that method.
Bill
 
Ashwin Desai
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
If you want to use the HTTP servlets, then, the service() method calls the appropriate doPost() / doGet() method based on the type of HTTP request. Thus, there is no need to use the service() method in HTTP servlets.
But, if you have your own protocol and want to use servlets to handle the request-responses then you will have to provide an implementation for the service () method so that the appropriate actions may be taken.
Hope this helps.
Ashwin.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic