1

我正在使用 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 上下文。

4

2 回答 2

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;

    // ...
}
于 2012-11-30T01:46:04.703 回答
0

改用javax.ws.rs.core.Context

@Context
public void setServletContext(ServletContext context) {
  // ...
}
于 2012-11-29T17:54:36.933 回答