在restful Web服务中访问HttpServletRequest对象

时间:2011-10-24 08:53:08

标签: java web-services rest cxf restful-authentication

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

@Resource
private WebServiceContext context;

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

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

但是这些东西在一个宁静的网络服务中无效。 我正在使用Apache CXF开发restful web服务。请告诉我如何才能访问HttpServletRequest对象。

2 个答案:

答案 0 :(得分:14)

我建议使用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()

您可以使用@Context注释来标记其他类型(例如ServletContext或HttpServletRequest)。见Context Annotations.

答案 1 :(得分:1)

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

@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();
    }
... 
}