Java - getServletContext().getAttribute()返回null

ssg*_*gao 1 java servlets

我有一个MainServletContextimplements ServletContextListener存储属性

public void contextInitialized(ServletContextEvent sce) {

    ServletContext servletContext = sce.getServletContext();

    // successfully get a non-null stockMap
    servletContext.setAttribute("stockMap", stockMap);
}
Run Code Online (Sandbox Code Playgroud)

我宣布它web.xml,它看起来像

  <listener>
        <listener-class>controller.MainServletContext</listener-class>
  </listener>
Run Code Online (Sandbox Code Playgroud)

现在我想stockMap从servlet类中获取它

Map<SimpleStock, Stock> stockMap = (Map<SimpleStock, Stock>) getServletContext().getAttribute("stockMap");
Run Code Online (Sandbox Code Playgroud)

我有一个NullPointerException.我可以问一下是否有任何缺失的步骤?

谢谢.

堆栈跟踪

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
controller.TopTenServlet.service(TopTenServlet.java:91)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Run Code Online (Sandbox Code Playgroud)

我的Servlet init方法

@Override
public void init(ServletConfig config) throws ServletException {
    this.servletConfig = config;
}
Run Code Online (Sandbox Code Playgroud)

Rav*_*yal 7

init(ServletConfig)错误地覆盖了你的方法.它应该是

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config); // would set: this.config = config;
    this.servletConfig = config;
}
Run Code Online (Sandbox Code Playgroud)

这就是为什么建议覆盖init(ServletConfig)但是init()方便的方法,因为它可以防止你遇到的完全相同的问题.

@Override
public void init() throws ServletException {
    this.servletConfig = config;
}
Run Code Online (Sandbox Code Playgroud)

基类GenericServlet#init(ServletConfig)会调用你init()

@Override
public void init(ServletConfig config) throws ServletException {
    this.config = config;
    this.init();
}
Run Code Online (Sandbox Code Playgroud)