aspose file tools*
The moose likes Servlets and the fly likes Why doPost and doGet and not everything in doService Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why doPost and doGet and not everything in doService" Watch "Why doPost and doGet and not everything in doService" New topic
Author

Why doPost and doGet and not everything in doService

Caesar Dutta
Ranch Hand

Joined: Sep 18, 2004
Posts: 30
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

Joined: Sep 22, 2001
Posts: 2578

It is always possible to find type of method in doService as well.

- Manish
Caesar Dutta
Ranch Hand

Joined: Sep 18, 2004
Posts: 30
Hi Manish,

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

Thanks,

Caesar
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
wht about this

request.getMethod();
Caesar Dutta
Ranch Hand

Joined: Sep 18, 2004
Posts: 30
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

Joined: Sep 23, 2004
Posts: 245
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.


<a href="http://forums.hotjoe.com/forums/list.page" target="_blank" rel="nofollow">Java forums using Java software</a> - Come and help get them started.
 
jQuery in Action, 2nd edition
 
subject: Why doPost and doGet and not everything in doService