[英]Java - getServletContext().getAttribute() returns null
I have a MainServletContext
that implements ServletContextListener
that stores an attribute 我有一个MainServletContext
,它implements ServletContextListener
,它存储了一个属性
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 我在web.xml
声明了它,看起来像
<listener>
<listener-class>controller.MainServletContext</listener-class>
</listener>
Now I want to get this stockMap
back from a servlet class 现在我想从servlet类取回这个stockMap
Map<SimpleStock, Stock> stockMap = (Map<SimpleStock, Stock>) getServletContext().getAttribute("stockMap");
I got a NullPointerException
. 我有一个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 我的Servlet初始化方法
@Override
public void init(ServletConfig config) throws ServletException {
this.servletConfig = config;
}
You've overridden your init(ServletConfig)
method incorrectly. 您错误地重写了init(ServletConfig)
方法。 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. 这就是为什么不建议重写init(ServletConfig)
而是使用init()
便捷方法的原因,因为它可以避免遇到与您完全相同的问题。
@Override
public void init() throws ServletException {
this.servletConfig = config;
}
The base class GenericServlet#init(ServletConfig)
would call your init()
as 基类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.