This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does a servlet has init method

 
Steve Grant
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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 ,
Steve
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13056
6
 
Malli Raman
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Malli's answer is a good one. When you have the init() method you can do things like the following:

MyClassWithLotsOfStaticMethods.setDbConnStr(getServletContext().getInitParameter("dbconn"));

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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic