Search code examples
javaweb-servicesrestcxfrestful-authentication

Getting Access to HttpServletRequest object in restful web service


I can get access to the HttpServlet Request object in a soap web service as follows: Declaring a private field for the WebServiceContext in the service implementation, and annotate it as a resource:

@Resource
private WebServiceContext context;

To get the HttpServletRequet object, I write the code as below:

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

But these things are not working in a restful web service. I am using Apache CXF for developing restful web service. Please tell me how can I get access to HttpServletRequest Object.


Solution

  • I'd recommend using 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()
    

    You can use the @Context annotation to flag other types (such as ServletContext or the HttpServletRequest specifically). See Context Annotations.