• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why init() when there is constructor?

 
Geeta Sawant
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why isn't constructor enough for initializing a servlet?

Thanks
Geeta
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65126
92
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because in the init call you usually want access to the servlet context and servlet config objects whch have yet to be created when the constructor would be called.
 
Eddy Lee Sin Ti
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The init() is part of the servlet life cycle management facility. Instead of using constructor, which is invoked when the instance is created, using a well defined, common life cycle method would help in more advanced management. In other words, the life cycle methods defined in javax.servlet.Servlet provide a contract where all servlet have to comply. You cant define constructor method in java interface right?
 
Paul Bourdeaux
Ranch Hand
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a often asked question in this forum, and rightfully so, as it is an important part of understanding the lifecycle of a servlet. Bear summed it up in his response, but if you want to see some more in depth answers, search this forum for "init() constructor" and you will find several threads dealing with this issue.

If you still have questions after looking, please post them!
 
sureshreddy puli
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is part of servlet life cycle designed by javasoft.And main purpose of init() is to retrive configuration parameters from web.xml.It is not possible to get initialization parameters through constructor and webcontainer accepts only default constructor. If u develop a servlet with parameterized constructor, it(webcontainer) raise an error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic