Java Servlet重写init(ServletConfig配置) [英] Java Servlets Overriding init(ServletConfig config)

查看:746
本文介绍了Java Servlet重写init(ServletConfig配置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to override init(ServletConfig config) method.My code is:

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

这是给出NullPointerException。

this is giving NullPointerException .

如果我将其修改为:

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

这很好用。
我知道我们应该覆盖init()方法而不是init(ServletConfig配置)但是

任何人都可以给我正确的理由为什么会发生这种情况?

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?

推荐答案

比较 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)时,首先必须做的是致电:

When overriding init(ServletConfig), the first thing that must be done is to call:

super.init(config);

如果你这样做,那么直接调用 getServletContext()将不再导致NPE。

If you do this then calling directly to getServletContext() in your method will no longer result in an NPE.

这篇关于Java Servlet重写init(ServletConfig配置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆