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.

Followers

Pageviews Last 7 Days