Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 441
Surya Avatar asked Oct 24 '11 08:10

Surya


People also ask

How do I pass HttpServletRequest in Java?

Show activity on this post. All the other answers are valid, but I would recommend you not to couple the XmlParser with HttpServletRequest. Retrieve all data you need from HttpServletRequest (an InputStream, which reads the body contents?) and pass it to the XmlParser.

Which method of the HttpServletRequest object is used?

Object of the HttpServletRequest is created by the Servlet container and, then, it is passed to the service method (doGet(), doPost(), etc.) of the Servlet.

How HttpServletRequest object is created?

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods ( doGet , doPost , etc). String identifier for Basic authentication. String identifier for Client Certificate authentication.

What is the difference between ServletRequest and HttpServletRequest?

ServletRequest provides basic setter and getter methods for requesting a Servlet, but it doesn't specify how to communicate. HttpServletRequest extends the Interface with getters for HTTP-communication (which is of course the most common way for communicating since Servlets mostly generate HTML).


Video Answer


1 Answers

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.

like image 57
kevinjansz Avatar answered Sep 30 '22 19:09

kevinjansz