6/10/2006

Why Servlet init Methods are Confusing

I wrote about servlet init methods in my previous post, A Common Mistake in Servlet init Methods. You may ask, what is the difference between servlet init() and init(ServletConfig), and why is it so confusing?

When servlet was invented, there was only one init method, the one with parameter ServletConfig. The no-arg init method was added around Servlet 2.3 timeframe, mainly to address this common mistake. This solution applies a Template Design Pattern to outline what needs to be done in init method and also keeps it extensible for concrete servlet classes.

init(ServletConfig) is the template method, which stores ServletConfig, and then delegates to init(). This is what javax.servlet.GenericServlet.init(ServletConfig) looks like:

public void init(ServletConfig config) throws ServletException {
this.config. = config;
init();
}
The real work of initialization is supposed to be done in init() method, which can be overrid by servlet subclasses. Its default implementation in javax.servlet.GenericServlet is merely a no-op.

From the above code snippet, when init() in your servlet class is invoked by the container, an instance of ServletConfig has already been saved. So you can safely call getServletConfig() inside of init() method.

Servlet classes rarely need to know about init(ServletConfig ) method. Only web containers need to invoke it. Ideally, this method should be declared as final or even private in GenericServlet. But that would break backward compatibility.

Having two overloaded init methods may also add to the confusion. Unless developers read the Javadoc carefully, their relationship (one calling the other) is unclear. So it's possible someone will override init() method like this:
@Override public void init() throws ServletException {
//do some initialization work first,
//then call init(ServletConfig)
init(null);
}
It will cause infinite loop and java.lang.StackOverflowError during servlet initialization, and the servlet will never be put into service. I hope I didn't make it more confusing. My previous post describes how to implement servlet init method.

3 comments:

Anonymous said...

Thanks you cleared a lot of confusion. The Javadocs don't mention which method calls which (init(ServletConfig) calls init())as clearly as you do.

Anonymous said...

Hi,
Thanks for such a nice article. to know more about init() calling.Please attach servlet-api-sources.jar in your IDE and can check how init(servletconfig) invoke init().

Thanks,
Pankaj

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai