我在web.xml配置文件中添加了一些参数,如下所示:
<context-param>
<param-name>service1</param-name>
<param-value>http://www.example.com/example2.html</param-value>
</context-param>
<context-param>
<param-name>service2</param-name>
<param-value>http://www.example.com/example2.html</param-value>
</context-param>
...
我尝试在我的servlet中获取参数,特别是在我的service方法中:
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(this.getServletContext().getInitParameter("service1"));
...
但在运行时我遇到了空指针异常... 我该如何获取包含在web.xml中的参数值?
以下是堆栈跟踪:
GRAVE: Servlet.service() for servlet DispatcherServlet threw exception
java.lang.NullPointerException
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:160)
at it.servlethope.DispatcherServlet.service(DispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
DispatcherServlet.java:66是我尝试使用getInitParameter()的代码行。
NullPointerException
异常。请发布堆栈跟踪并指出实际的代码行。 - BalusCthis.getServletContext()
是null
,那么它就会出现问题,但我想不出为什么会发生这种情况。 - skaffman