Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the reason for overriding the doGet() or doPost() method

 
maggie bosco
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the reason for overriding the doGet() or doPost() method in a Servlet?
I know it should be overriden ,but wat's the reason.
 
Paul Bourdeaux
Ranch Hand
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a nutshell, the doGet() and doPost() methods correspond to a HTTP method call that comes into the container. If a GET request (like that of a simple hyper link) is made to the url mapped to your servlet, then the service method will call the doGet() logic. If a POST request comes in (like when submitting a form), then the doPost() method will be called.

FYI, there is a do***() method for almost every HTTP method calls. Outside GET and POST, there is also HEAD, TRACE, OPTIONS, PUT, and DELETE. For the most part, though, you will probably only use doGet() and doPost().
 
jiju ka
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to Paul Bourdeaux notes...

Your servlet is extending HttpServlet. The service method of HttpServlet is calling the doGet and doPost method of your servlet. If you override service method the same will not happen. In this case every get and post operations will be handled by the overridden service method - means: "If you override service method doGet and doPost will not get executed instead service will get executed"
 
Paul Bourdeaux
Ranch Hand
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"If you override service method doGet and doPost will not get executed instead service will get executed"

True, but you should never override the service method. The service() method supplied by HttpServlet looks at the incoming HTTP request, and determines which doXXX() method should be called. It is extremely unlikely that you have any reason to change this implementation.
 
jiju ka
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It is extremely unlikely that you have any reason to change this implementation.


Since service method is not final, it is likely that service method will be overridden. This is my point. Thanks for directing this way.

I have seen it in lot of code and in some custom built java framework intended to use throughout certain enterprise.

The designer should be aware of the problems created by this approach. One problem is that it will create ineffeciency in dealing with the "multiple post" problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic