Getting Access to HttpServletRequest object in res

2019-03-25 03:39发布

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.

2条回答
Evening l夕情丶
2楼-- · 2019-03-25 03:54

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();
    }
... 
}
查看更多
Fickle 薄情
3楼-- · 2019-03-25 04:17

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.

查看更多
登录 后发表回答