PDA

View Full Version : super.init(config) in java 2011



saneha
04-24-2011, 10:41 PM
super.init(config);

you use the above line of code in the "Reading init Parameters" example. my question is that what is the function of the above said line of code.

Vuhelper
04-24-2011, 10:43 PM
The reason is that a servlet is passed its ServletConfig instance in its init() method, but not in any other method. This could cause a problem for a servlet that needs to access its config object outside of init(). Calling super.init(config) solves this problem by invoking the init() method of GenericServlet, which saves a reference to the config object for future use.


So, how does a servlet make use of this saved reference? By invoking methods on itself. The GenericServlet class itself implements the ServletConfig interface, using the saved config object in the implementation. In other words, after the call to super.init(config), a servlet can invoke its own getInitParameter() method. That means we could replace the following call:

String initial = config.getInitParameter("initial");

with:

String initial = getInitParameter("initial");

This second style works even outside of the init() method. Just remember, without the call to super.init(config) in the init() method, any call to the GenericServlet's implementation of getInitParameter() or any other ServletConfig methods will throw a NullPointerException. So, let us say it again: every servlet's init() method should call super.init(config) as its first action. The only reason not to is if the servlet directly implements the javax.servlet.Servlet interface, where there is no super.init().