• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Why does a servlet has init method

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See this recent discussion for exhaustive discussion.
Bill
 
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Just let me do the talking. Ahem ... so ... you see ... we have this tiny ad...
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic