繁体   English   中英

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

[英]Java - getServletContext().getAttribute() returns null

我有一个MainServletContext ,它implements ServletContextListener ,它存储了一个属性

public void contextInitialized(ServletContextEvent sce) {

    ServletContext servletContext = sce.getServletContext();

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

我在web.xml声明了它,看起来像

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

现在我想从servlet类取回这个stockMap

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

我有一个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)

我的Servlet初始化方法

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

您错误地重写了init(ServletConfig)方法。 它应该是

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

这就是为什么建议重写init(ServletConfig)而是使用init()便捷方法的原因,因为它可以避免遇到与您完全相同的问题。

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

基类GenericServlet#init(ServletConfig)将调用您的init()

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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