This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Servlets and the fly likes Correlation between Servlet's init() and service() methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Correlation between Servlet Watch "Correlation between Servlet New topic

Correlation between Servlet's init() and service() methods

Ramaswamy Srinivasan
Ranch Hand

Joined: Aug 31, 2004
Posts: 295
Dear Ranchers,

One of my friends got this question, as a part of his interview questions. We have been thinking about this, from then on. We would like to have a better understanding. That brings us here...well, the question is...

Can service() method be called from init() method? If so, what's the use of having a separate service method.

We know that it's a lifecycle method and init() will pass the Request,Response objects to the service method. Can you please care to expand a bit on these?

Your help is much appreciated.

Ben Souther

Joined: Dec 11, 2004
Posts: 13410

No, the init method (as it's name implies) gets run when the servlet is loaded. The service method on the other hand, waits for requests and responds to them.
Look at the argument list for service. It requires a request and response object.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Shrinivas Mujumdar
Ranch Hand

Joined: Aug 27, 2004
Posts: 328
Hello Ramaswamy ,
init() is called only once & not for each request & also if you try to call service from init how you will get Request & Response Object. Somehow suppose you get them then as said earlier,init will be called only once.

I hope this helps.......

By the way if you don't mind what was your friends answer & where he got that job?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
Anybody contemplating working seriously with servlets and JSP should have a copy of the API on hand to refer to. It really is very clear on such things as the role of init and service - why ask questions on this forum when you could refer to the source?

Download links to the specifications can be found here for the 2.2, 2.3 and 2.4 APIs.
I agree. Here's the link:
subject: Correlation between Servlet's init() and service() methods
It's not a secret anymore!