在 restful Web 服务中获取对 HttpServletRequest 对象的访问权限

我可以访问 soap Web 服务中的 HttpServlet Request 对象,如下所示:在服务实现中声明 WebServiceContext 的私有字段,并将其注释为资源:

@Resource
private WebServiceContext context;

为了获取 HttpServletRequet 对象,我编写了如下代码:

MessageContext ctx = context.getMessageContext();
HttpServletRequest request =(HttpServletRequest)ctx.get(AbstractHTTPDestination.HTTP_REQUEST);

但是这些东西在宁静的Web服务中不起作用。我正在使用Apache CXF来开发宁静的Web服务。请告诉我如何访问HttpServletRequest Object。


答案 1

我建议使用org.apache.cxf.jaxrs.ext.MessageContext

import javax.ws.rs.core.Context;
import org.apache.cxf.jaxrs.ext.MessageContext;

...
// add the attribute to your implementation
@Context 
private MessageContext context;

...
// then you can access the request/response/session etc in your methods
HttpServletRequest req = context.getHttpServletRequest();
HttpServletResponse res = context.getHttpServletResponse()

您可以使用注释来标记其他类型(例如 ServletContext 或 HttpServletRequest)。请参见上下文批注。@Context


答案 2

将此代码用于访问请求和每个请求的响应:

@Path("/User")
public class RestClass{

    @GET
    @Path("/getUserInfo")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUserrDetails(@Context HttpServletRequest request,
            @Context HttpServletResponse response) {
        String username = request.getParameter("txt_username");
        String password = request.getParameter("txt_password");
        System.out.println(username);
        System.out.println(password);

        User user = new User(username, password);

        return Response.ok().status(200).entity(user).build();
    }
... 
}