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

Why doPost and doGet and not everything in doService

 
Caesar Dutta
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was aksed in an interview the question "Why doPost and doGet and not everything in doService?". Please clarify whether my answer was correct.

"It is the GenericServlet's service method which calls the HttpServlet's
service method. The Http's servlet's service method analyzes the request and
calls the corresponding doXXX() method.

Now it is true that if I override the service method then doGet and doPost
will not be called.

But if I want specific actions for doGet then the problem is that my doGet
method will not be called and it is not possible to find out what the
request was so that I can separate code within the doService method like
if (request type is GET) {
//do Get action
} else {
//do post action
}
"

It seemed that they were not satisfied and never expected this from. Is
there a better explanation

Regards,

Caesar
 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is always possible to find type of method in doService as well.

- Manish
 
Caesar Dutta
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Manish,

Can you please provide a code snippet to find out request type.

Thanks,

Caesar
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wht about this

request.getMethod();
 
Caesar Dutta
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much Adeel and Manish.

But my original question is still not answered. Why not everything
in Service method? Why do we have doXXX() methods?

Thanks again,

Caesar
 
Scott Dunbar
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember, service() is a method defined in Servlet, not HttpServlet. A servlet is meant to be protocol independent. While most people do use it with HTTP, that is not a requirement. When you write your own HttpServlet you are making your life easier by not having to do a switch type of statment for each of the HTTP actions. But if you had, say, an SMTPServlet, it might have methods something like doAutn() and doData(). Or an FTPServlet might have doPut() and doLS(). In those cases it would be protocol specific.

I'm not sure if that answered your question or not. For HttpServlets it is simply not having to reinvent something that already exists.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic