简体   繁体   中英

Java - getServletContext().getAttribute() returns null

I have a MainServletContext that implements ServletContextListener that stores an attribute

public void contextInitialized(ServletContextEvent sce) {

    ServletContext servletContext = sce.getServletContext();

    // successfully get a non-null stockMap
    servletContext.setAttribute("stockMap", stockMap);
}

I declared it in web.xml , it looks like

  <listener>
        <listener-class>controller.MainServletContext</listener-class>
  </listener>

Now I want to get this stockMap back from a servlet class

Map<SimpleStock, Stock> stockMap = (Map<SimpleStock, Stock>) getServletContext().getAttribute("stockMap");

I got a NullPointerException . May I ask if there's any step missing?

Thanks.

Stacktrace

java.lang.NullPointerException
javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
controller.TopTenServlet.service(TopTenServlet.java:91)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

My Servlet init method

@Override
public void init(ServletConfig config) throws ServletException {
    this.servletConfig = config;
}

You've overridden your init(ServletConfig) method incorrectly. It should be

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

This is why it's not recommended to override init(ServletConfig) but the init() convenience method as it prevents the exact same problem you've run into.

@Override
public void init() throws ServletException {
    this.servletConfig = config;
}

The base class GenericServlet#init(ServletConfig) would call your init() as

@Override
public void init(ServletConfig config) throws ServletException {
    this.config = config;
    this.init();
}

我怀疑您有一个不调用super(config)的servlet init(ServletConfig config)方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM