Java GetServletContext在扩展HttpServlet的类中返回null

Java GetServletContext在扩展HttpServlet的类中返回null,java,servlets,Java,Servlets,所以我有一个扩展HttpServlet的类,我试图访问实现ServletContextListener的不同类中设置的变量 但是,扩展HttpServlet的类中的以下代码行给出了NullPOinterException: SomeObject x = getServletContext().getAttribute("x"); 我不明白为什么会这样。有什么想法吗?可能,您已经在Servlet类中重写了init(ServletConfig cfg)方法,并且没有调用super.init(cf

所以我有一个扩展HttpServlet的类,我试图访问实现ServletContextListener的不同类中设置的变量

但是,扩展HttpServlet的类中的以下代码行给出了NullPOinterException:

SomeObject x =  getServletContext().getAttribute("x");

我不明白为什么会这样。有什么想法吗?

可能,您已经在Servlet类中重写了init(ServletConfig cfg)方法,并且没有调用super.init(cfg)来执行标准的设置工作,从而导致了一个空的上下文。

应用程序部署在哪个web容器上?
int x=getServletContext().getAttribute(“x”)
这会编译吗?@zaffargchal:on Winstone,我也在尝试让它在Tomcat上工作。@JigarJoshi:是的,它会编译,但HttpServlet.getServletContext().getAttribute(String)返回对象,不是int。因此它不会编译,除非您的代码中有不同的内容。我根本没有实现init方法。@redman可能您正在使用IDE生成的类来重写它?我意外地重写了init(ServletConfig cfg)方法,并将方法体保留为空。删除此方法定义后,getServletContext()起作用。谢谢