This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Malatesh Karabisti wrote:why I can't write my own constructor in Servlet?
You can. What is preventing you?
what are the consequence if I write it?
Everyone will think that you don't know what you are doing.
Can any body please explain ?
The init() method is the proper place to initialize a servlet as the ServletConfig instance has been established by then. Constructors are not useful and are not usually used (I have, in fact, never written a servlet constructor in over a decade of writing servlets).
No my doubt is not clear. This question is asked in one of the interviews what would be the proper answer ?please elaborate.
I gave the reply like we should not write the constructor container will do for us. That is not a proper answer I know.
Malatesh Karabisti wrote:why I can't write my own constructor in Servlet ?what are the consequence if I write it?
I guess you are talking about non-default constructors.
You can write a servlet that has the default constructor plus other constructors, but only default constructor will be used by the container to instantiate your servlet. Please remember the container only knows about the javax.servlet.Servlet interface. Once the servlet object has been instantiated or created, the container will invoke the init(ServletConfig) method and let the servlet initialize itself before serving any requests. The init method is the proper place for the initialization, as it is able to access the environment through the ServletConfig.
public void init() throws ServletException
This method is provided as a convenience so that servlet writers do not have to worry about storing the ServletConfig object. When extending this class, simply override this method and it will be called by GenericServlet.init(ServletConfig config);
Can you please explain this ?
Joined: Jun 25, 2002
The web container only knows about the Servlet interface, which defines the init(ServletConfig) method.
The GenericServlet is a helper class that makes writing servlets easier. The init() method of the GenericServlet (as you stated that) is a convenience method so that there's no need to call super.init(config). Please check the API for the details.
Please also note that you can develop your servlet from scratch, i.e. without extending the GenericServlet class or the HttpServlet class.