wood burning stoves 2.0*
The moose likes Servlets and the fly likes can init() be replaced in servlet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "can init() be replaced in servlet?" Watch "can init() be replaced in servlet?" New topic
Author

can init() be replaced in servlet?

naresh Addanki
Greenhorn

Joined: Feb 21, 2007
Posts: 2
Can the init() method in the servlet be replaced by the constructor?
Sridhar Darbha
Greenhorn

Joined: Dec 12, 2006
Posts: 14
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
Marshal

Joined: Mar 22, 2005
Posts: 42634
    
  65
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.


Ping & DNS - my free Android networking tools app
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can init() be replaced in servlet?