Java Servlet重写init(ServletConfig配置)

Rit*_*hik 8 java servlets init

我试图覆盖init(ServletConfig配置)方法.我的代码是:

 public void init(ServletConfig config) throws ServletException {
    ServletContext sc = getServletContext(); // ----- NullPointerException
}
Run Code Online (Sandbox Code Playgroud)

这是给出NullPointerException.

如果我将其修改为:

   public void init(ServletConfig config) throws ServletException {
    ServletContext sc = config.getServletContext(); // ----- works fine
}
Run Code Online (Sandbox Code Playgroud)

这很好用.我知道我们应该覆盖init()方法而不是init(ServletConfig配置),但
任何人都可以给我正确的理由,为什么会发生这种情况?

Per*_*ion 20

比较以下文档init(ServletConfig):

public void init(ServletConfig config)throws ServletException
Called by the servlet container to indicate to a servlet that the servlet
is being placed into service.

See Servlet#init. This implementation stores the ServletConfig object
it receives from the servlet container for later use. When overriding
this form of the method, call super.init(config).

并将其与以下文档进行比较init():

public void init() throws ServletException
A convenience method which can be overridden so that there's no need to
call super.init(config).

Instead of overriding init(ServletConfig), simply override this method
and it will be called by GenericServlet.init(ServletConfig config). The
ServletConfig object can still be retrieved via getServletConfig().

覆盖时init(ServletConfig),必须要做的第一件事就是调用:

super.init(config);
Run Code Online (Sandbox Code Playgroud)

如果您这样做,那么直接调用getServletContext()您的方法将不再导致NPE.