init
methods allows a servlet to perform one-time initialization prior to servicing requests. One common mistake when implementing init
method is in this form:public void init(ServletConfig config)This is wrong because it doesn't invoke
throws ServletException {
//do custom initialization ...
System.out.println(" init(ServletConfig config) invoked.");
...
}
super.init(ServletConfig)
. As a result, ServletConfig
is not stored in the servlet instance, and subsequent calls to getServletConfig will return null.Another variant of this mistake is to store the
ServletConfig
parameter in a class variable of the concrete servlet class:private ServletConfig config;This is also wrong because
public void init(ServletConfig config)
throws ServletException {
this.config = config;
System.out.println(" init(ServletConfig config) invoked.");
//do custom initialization ...
...
}
config
saved in the current servlet won't be available to its superclass, usually GenericServlet
or HttpServlet
. When the default implementation of getServletConfig()
method looks for ServletConfig
in superclasses, it's still null. The only way it can work is that you also override getServletConfig
method to look in the concrete servlet class, which is unusual and unnecessary.This is the error from Glassfish/SJSAS 9.0/JavaEE SDK 5, when running a servlet with those incorrect
init
methods:java.lang.NullPointerExceptionTo implement servlet
test.HelloWorldServlet.doGet(HelloWorldServlet.java:14)
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:73)
com.sun.enterprise.web.VirtualServerPipeline.invoke(VirtualServerPipeline.java:120)
org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:231)
init
methods correctly, you have several options:- If you only need to save
ServletConfig
, do not override anyinit
methods in servlet class. It's already implemented in servlet superclassGenericServlet
. - If you have custom initialization work to do, override the no-arg
init()
method, and forget aboutinit(ServletConfig)
. Is it ok to callgetServletConfig()
method inside the no-arginit()
method? Yes, an instance ofServletConfig
has already been saved by superclassGenericServlet
. See Why Servlet init Methods are Confusing for more details. - If you really want to override
init(ServletConfig)
, make sure you invokesuper.init(ServletConfig);
, usually as the first line, though it's not strictly required.