我正在使用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();
}
}
例外是:
java.lang.NullPointerException at com.webservices.server.WebServer.createTrackInJSON(WebServer.java:36) ... servletContext为null
请帮我确定如何在Web服务中获取servlet上下文。
答案 0 :(得分:3)
使用@Context注释,并注入正确的类。您也可以直接注入servlet请求和响应对象。
import jax.ws.rs.core.Context;
@Path("/server")
public class WebServer {
@Context
private ServletContext context;
@Context
private HttpServletRequest request;
@Context
private HttpServletResponse response;
// ...
}
答案 1 :(得分:0)
@Context
public void setServletContext(ServletContext context) {
// ...
}