Java Servlet重写init(ServletConfig配置)

时间:2012-11-30 04:24:49

标签: java servlets init

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

 public void init(ServletConfig config) throws ServletException {
    ServletContext sc = getServletContext(); // ----- NullPointerException
}

这是给出NullPointerException。

如果我将其修改为:

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

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

4 个答案:

答案 0 :(得分:19)

比较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);

如果您这样做,那么直接致电您方法中的getServletContext()将不再导致NPE。

答案 1 :(得分:2)

这是因为您重写了错误的方法机制 如果你重写

     public void init(ServletConfig config) throws ServletException {
        super.init(config);
            ServletContext sc = getServletContext(); 
     }

而不是覆盖init(ServletConfig),只需覆盖以下方法,它就会被GenericServlet.init(ServletConfig config)

调用
 public void init() throws ServletException {
 ServletContext sc = getServletContext(); 
}

答案 2 :(得分:1)

因为在:

public void init(ServletConfig config) throws ServletException
{
    ServletContext sc = getServletContext();
}

您不会调用super.init(ServletConfig)。因此,ServletConfig不存储在servlet实例中,随后对getServletConfig的调用将返回null。

答案 3 :(得分:0)

只需将super init(config)置于重写方法的第一行

即可
public void init(ServletConfig config) throws ServletException