我尝试将我的应用程序部署到带有Metro/Jersey和Glassfish 3.1.2的Tomcat 6,但访问WebServiceContext资源总是会导致空指针异常,除非我使用自动生成的Glassfish测试门户测试应用程序.
这是我写的一个简单的测试方法,用于验证:
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@WebService
@Path("/test")
public class Test {
@Resource
WebServiceContext wsContext;
@GET
@Produces("text/plain")
@Path("/hello")
public String hello() {
MessageContext mc = wsContext.getMessageContext(); // NULL POINT HAPPENS HERE!
ServletContext servletContext = (ServletContext)
mc.get(
MessageContext.SERVLET_CONTEXT);
String s = servletContext.getRealPath("/WEB-INF");
return "Real Path: " + s;
}
}
Run Code Online (Sandbox Code Playgroud)
这里是相应的web-xml(主要由Eclipse自动生成):
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>WebApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file> …Run Code Online (Sandbox Code Playgroud)