我正在使用 Jersey 开发 REST Web 服务,我需要从 Web 服务方法调用一个 servlet 来对用户进行身份验证。运行以下代码时出现异常:
@Path("/server")
public class WebServer {
@Resource
private WebServiceContext context;
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) throws IOException, ServletException {
ServletContext servletContext = (ServletContext) context.getMessageContext()
.get(MessageContext.SERVLET_CONTEXT); // Here I am getting NPE
HttpServletRequest request = (HttpServletRequest) context.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
HttpServletResponse response = (HttpServletResponse) context.getMessageContext()
.get(MessageContext.SERVLET_RESPONSE);
request.setAttribute("username", track.getUsername());
request.setAttribute("password", track.getPassword());
servletContext.getRequestDispatcher("/LoginAction").include(request, response);
String loginStatus = request.getParameter("loginStatus");
String Token = request.getParameter("Token");
String result = ""+track;
return Response.status(200).entity(result).build();
}
}
例外是:
com.webservices.server.WebServer.createTrackInJSON(WebServer.java:36) 处的 java.lang.NullPointerException ...servletContext 为空
请帮助我确定如何在 Web 服务中获取 servlet 上下文。