Getting Access to HttpServletRequest object in restful web service

Surya picture Surya · Oct 24, 2011 · Viewed 43k times · Source

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.

Answer

kevinjansz picture kevinjansz · Oct 28, 2011

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.