Getting Access to HttpServletRequest object in res

2019-03-25 04:08发布

问题:

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.

回答1:

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.



回答2:

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