17

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.

Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69
Surya
  • 494
  • 3
  • 11
  • 23

2 Answers2

14

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.

kevinjansz
  • 638
  • 6
  • 20
  • 4
    In the Jersey implementation, `MessageContext` does not work. But you can still use `@Context HttpServletRequest`. – kxsong Nov 25 '14 at 16:40
  • I could not get your example to work. I was only able to get a reference to the HttpServletRequest by adding it as a method parameter decorated with the @Context annotation as shown below. – Eric Green Sep 23 '18 at 19:09
4

use this code for access request and response for each request:

@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();
    }
... 
}
M2E67
  • 937
  • 7
  • 23