Java getServletContext NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19778774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getServletContext NullPointerException
提问by Threadid
I know this question has been asked a million times and there are 5 million answers - some or which are very informative. None of which have solved this problem.
我知道这个问题已经被问了一百万次,有 500 万个答案——其中一些或其中的信息非常丰富。没有一个解决了这个问题。
My goal is similar to many of the others - I want to access files - images, svgfiles, templates, etc. in the web app run-time environment. I can make it work if I simply hard wire the directory path. However, I would like to make my servlet portable and use a relative reference to access these resources -if for no other reason I develop in Windows and deploy in Linux.
我的目标与许多其他目标类似 - 我想在 Web 应用程序运行时环境中访问文件 - 图像、svgfiles、模板等。如果我只是硬连线目录路径,我就可以让它工作。但是,我想让我的 servlet 可移植并使用相对引用来访问这些资源 - 如果没有其他原因我在 Windows 中开发并在 Linux 中部署。
The basic problem is that getServletContext() is null and I am unable to determine why.
基本问题是 getServletContext() 为空,我无法确定原因。
Below is the error message, the code that produced it, followed by environment details. Produces the same error in both development and production. I will be happy to provide any additional details if requested.
下面是错误消息、产生它的代码,然后是环境详细信息。在开发和生产中产生相同的错误。如果需要,我很乐意提供任何其他详细信息。
Please explain what I need to do to get this working? I will be eternally grateful. Regards
请解释我需要做什么才能使其正常工作?我将永远感激。问候
SEVERE: Servlet.service() for servlet [jsp] in context with path [/HelloWorld] threw exception [An exception occurred processing JSP page /hello.jsp at line 19
16: <title>Hello World</title>
17: </head>
18: <body>
19: <%=wtGreet.getGreeting()%>
20: </body>
21: </html>
Stacktrace:] with root cause
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
at HelloWorld.Greeting.getGreeting(Greeting.java:23)
at org.apache.jsp.hello_jsp._jspService(hello_jsp.java:91)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
HelloWorld application works - produces undesired error - exactly the same as the real thing.
HelloWorld 应用程序工作 - 产生意外错误 - 与真实情况完全相同。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF 8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="wtGreet" scope="page"
class="HelloWorld.Greeting">
<jsp:setProperty name="wtGreet" property="who" value="World"/>
<jsp:setProperty name="wtGreet" property="greet" value="Hello"/>
</jsp:useBean>
<jsp:setProperty name="wtGreet" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello World</title>
</head>
<body>
<%=wtGreet.getGreeting()%>
</body>
</html>
Then Servlet that the jsp calls
然后是jsp调用的Servlet
package HelloWorld;
import javax.servlet.http.HttpServlet;
public class Greeting extends HttpServlet {
private static final long serialVersionUID = 1298516959968350334L;
private String who;
private String greet;
public void setWho(String who) {
this.who = who;
}
public void setGreet(String greet) {
this.greet = greet;
}
public String getGreeting() {
System.out.println("getServletContext() == null :" + getServletContext().getContextPath());
return "<p>" + this.greet + " " + this.who + "</P>";
}
}
Development EnvironmentWindows Eclipse JEE Apache Tomcat 7 JRE 7
开发环境Windows Eclipse JEE Apache Tomcat 7 JRE 7
Production EnvironmentLinux Apache Tomcat 7 JRE 8
生产环境Linux Apache Tomcat 7 JRE 8
采纳答案by A4L
Based on the last element of your stack trace
基于堆栈跟踪的最后一个元素
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
the method getServletContext()
is called and the exception happens in the line 125
in the class javax.servlet.GenericServlet
.
该方法getServletContext()
被调用,异常发生在125
类中的行中javax.servlet.GenericServlet
。
If getServletContext()
had returned null
then the last stack trace element would have been
如果getServletContext()
已返回,null
则最后一个堆栈跟踪元素将是
at HelloWorld.Greeting.getGreeting(Greeting.java:23)
According to this codeof javax.servlet.GenericServlet
the method getServletConfig()
is the one returning null
, i.e. you servlet is not configured.
根据这个代码的javax.servlet.GenericServlet
方法getServletConfig()
是一个回归null
,即你的servlet没有配置。
This might be because you are (mis)using a servlet as a bean in your jsp
这可能是因为您(错误地)将 servlet 用作 jsp 中的 bean
<jsp:useBean id="wtGreet" scope="page" class="HelloWorld.Greeting">
and that servlet is not properly initialized.
并且该 servlet 未正确初始化。
Servlets are not meant to be used like that. You may want to use a simple JavaBeanand have it have a method getGreeting()
.
Servlet 不应该这样使用。您可能想使用一个简单的JavaBean并让它有一个方法getGreeting()
。
To get the ServletContext
inside your jsp you may use the implicit object application
, See herefor other available implicit objects in the jsp.
要获取ServletContext
您的 jsp 内部,您可以使用隐式对象application
,请参阅此处了解 jsp 中其他可用的隐式对象。
回答by Threadid
Even though the final solution is to implement a Model 2 pattern (I will include when finished), there is a good working answer for the question as asked. Thanks to A4L for showing the way.
尽管最终的解决方案是实现模型 2 模式(完成后我会包括在内),但对于所提出的问题,有一个很好的工作答案。感谢 A4L 为我们指明了方向。
Working from the understanding that the jsp engine compiles the jsp into a servlet and loads it into the servlet engine, the jsp implicit objects can be used to access an instantiated javax.servlet object.
根据jsp 引擎将jsp 编译成servlet 并将其加载到servlet 引擎的理解,jsp 隐式对象可用于访问实例化的javax.servlet 对象。
The HelloWorld example is changed as follows: 1) Remove import javax.servlet.http.HttpServlet; and extends HttpServlet because this does nothing. 2) Add an attribute of type ServletContext and populate the attribute using the setter from the jsp page.
HelloWorld 示例更改如下: 1) 删除 import javax.servlet.http.HttpServlet; 并扩展 HttpServlet 因为这什么都不做。2) 添加 ServletContext 类型的属性,并使用 jsp 页面中的 setter 填充该属性。
Any object that is available to the servlet can be available to the bean by way of jsp implicit objects.
任何对 servlet 可用的对象都可以通过 jsp 隐式对象对 bean 可用。
jsp
jsp
{<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="wtGreet" scope="page"
class="HelloWorld.Greeting">
<jsp:setProperty name="wtGreet" property="who" value="World"/>
<jsp:setProperty name="wtGreet" property="greet" value="Hello"/>
</jsp:useBean>
<jsp:setProperty name="wtGreet" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
<%wtGreet.setSc(application.getContext("/HelloWorld"));%>
<%=wtGreet.getGreeting()%>
</body>
</html>}
Bean
豆角,扁豆
package HelloWorld;
import javax.servlet.ServletContext;
public class Greeting {
private String who;
private String greet;
private ServletContext sc;
public void setSc(ServletContext sc) {
this.sc = sc;
}
public void setWho(String who) {
this.who = who;
}
public void setGreet(String greet) {
this.greet = greet;
}
public String getGreeting() {
return "<p>" + this.greet + " " + this.who + " from \"Context Path\" " + sc.getContextPath() + "</P>";
}
}