我正在尝试覆盖初始化(ServletConfig配置) method.My代码是:
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配置),但是
谁能给我一个合理的理由来解释为什么会发生这样的事情?
发布于 2012-11-30 12:43:29
发生这种情况的原因是,如果重写
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext sc = getServletContext();
}只需覆盖下面的方法,GenericServlet.init(ServletConfig config)就会调用它,而不是覆盖init(ServletConfig)
public void init() throws ServletException {
ServletContext sc = getServletContext();
}发布于 2012-11-30 12:41:24
因为在:
public void init(ServletConfig config) throws ServletException
{
ServletContext sc = getServletContext();
}您不会调用super.init(ServletConfig)。因此,ServletConfig不会存储在servlet实例中,后续对getServletConfig的调用将返回null。
发布于 2014-06-05 13:50:33
只需将超级初始化(Config)放在被覆盖方法的第一行
public void init(ServletConfig config) throws ServletExceptionhttps://stackoverflow.com/questions/13638978
复制相似问题