Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can init() be replaced in servlet?

 
naresh Addanki
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can the init() method in the servlet be replaced by the constructor?
 
Sridhar Darbha
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig.


I think a more likely explanation is that servlets are constructed from the class name given in web.xml, where no provisions for constructor parameters can be defined. Java 1.1 -which introduced reflection- predates the Servlet specification.

In addition, having an init method makes it possible to include it in the Servlet interface, thus forcing the developer to implement it. This is similar to applets, where the constructor plays no particular role, but the lifecycle methods of interface Applet do.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic