gpt4 book ai didi

Java Servlets 覆盖 init(ServletConfig 配置)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:29:32 25 4
gpt4 key购买 nike

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

 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 config) 但是
谁能告诉我为什么会这样?

最佳答案

比较init(ServletConfig)的文档:

public void init(ServletConfig config)throws ServletExceptionCalled by the servlet container to indicate to a servlet that the servletis being placed into service.See Servlet#init. This implementation stores the ServletConfig objectit receives from the servlet container for later use. When overridingthis form of the method, call super.init(config).

And compare that with the documentation for init():

public void init() throws ServletExceptionA convenience method which can be overridden so that there's no need tocall super.init(config).Instead of overriding init(ServletConfig), simply override this methodand it will be called by GenericServlet.init(ServletConfig config). TheServletConfig object can still be retrieved via getServletConfig().

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

super.init(config);

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

关于Java Servlets 覆盖 init(ServletConfig 配置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com