Saturday, May 21, 2011

The Servlet init Vs Constructor

Generally Servlets don’t have the Constructor, because a servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should be place in the init(), since it get called when the servlet is first loaded.

You cann’t use a Constructor instead of init() method to initialize a servlet.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 constructor 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. 

Even while you trying to override the init() method you should pass the argument a ServletContext object because the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.

3 comments:

ramesh sadasivam said...

Dear friend,

Thanks for voting for my video on Indiblogger.

Web Hosting India said...

Hello friend..Servlet init is effective information for us.Thanks for sharing.

Free Hosting said...

Never seen a website like this.Its more helpful info for all of the visitors.Thanks for your marvelous posting.