I am trying to override init(ServletConfig config) method.My code is:
public void init(ServletConfig config) throws ServletException {
ServletContext sc = getServletContext(); // ----- NullPointerException
}
this is giving NullPointerException .
If i modify it as:
public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext(); // ----- works fine
}
This works fine.
I know that we should override init() method and not init(ServletConfig config) but
Can anybody give me proper reason as why this is happening?
Compare the documentation for
init(ServletConfig):And compare that with the documentation for
init():When overriding
init(ServletConfig), the first thing that must be done is to call:If you do this then calling directly to
getServletContext()in your method will no longer result in an NPE.