File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Why does a servlet has init method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why does a servlet has init method" Watch "Why does a servlet has init method" New topic

Why does a servlet has init method

Steve Grant
Ranch Hand

Joined: Nov 24, 2003
Posts: 106
This question is on servlet.
Why cant we use constructor of a servlet class as a initializer
for that servlet instead of init() method.
Why we need init method when we can use non-argument
constructor as initializer for that servlet.
I know that init method has something to do with the life cycle of
servlet. But still cant we use constructor instead of init method.

Thx ,

SCJP1.4<br />IBM Certified System Administrator -- WebSphere Application Server V5.0 (340)
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
See this recent discussion for exhaustive discussion.
Malli Raman
Ranch Hand

Joined: Nov 07, 2001
Posts: 312
1. I think it is the way you can seperate the initialization logic with basic default construction to make easy for the reusability.

2. The container will always instantiate the servlet with the default constructor and you won't get the servlet config object in the default constructor method, which is used to get the servlet configuration details, servletContext details.
M. Gagnon
Ranch Hand

Joined: Feb 18, 2004
Posts: 68
I think Malli's answer is a good one. When you have the init() method you can do things like the following:


With the above I can simply change the database connection string I need in the deployment descriptor when I change from one environment to another with no need to recompile anything. Way cool!
I agree. Here's the link:
subject: Why does a servlet has init method
It's not a secret anymore!