30

Is it possible to access the Request object in a REST method under JAX-RS?

I just found out

@Context Request request;
0

2 Answers 2

68

On JAX-RS you must annotate a Request parameter with @Context:

 @GET  
 public Response foo(@Context Request request) {

 }

Optionally you can also inject:

18

To elaborate on @dfa's answer for alternatives, I find this to be simpler than specifying the variable on each resource method signature:

public class MyResource {

  @Context
  private HttpServletRequest httpRequest;

  @GET  
  public Response foo() {  
    httpRequest.getContentType(); //or whatever else you want to do with it
  }
}
6
  • 1
    Any of this above don't work when I try to invoke the REST api from Junit. The request comes as null. Commented Mar 17, 2016 at 12:10
  • This may not work in later versions of Dropwizard @DebaprasadJana - this was for Dropwizard 0.7.x
    – th3morg
    Commented Mar 17, 2016 at 12:34
  • Are there any concurrency issues with this approach?
    – Dragas
    Commented Sep 7, 2018 at 5:20
  • @Dragas every request to the application will have its own thread, so there will not be a problem with concurrency.
    – th3morg
    Commented Sep 7, 2018 at 9:35
  • But controllers that contain @Path annotations are singletons, aren't they? Does that not mean that if your request takes long enough, eventually your thread will update with another requests metadata?
    – Dragas
    Commented Sep 7, 2018 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.