27

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

I just found out

@Context Request request;
cassiomolin
  • 113,708
  • 29
  • 249
  • 319
qnoid
  • 2,296
  • 2
  • 26
  • 43

2 Answers2

63

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

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

 }

Optionally you can also inject:

cassiomolin
  • 113,708
  • 29
  • 249
  • 319
dfa
  • 111,277
  • 30
  • 187
  • 226
17

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
  }
}
Jens Piegsa
  • 7,094
  • 5
  • 58
  • 102
th3morg
  • 3,921
  • 1
  • 29
  • 44
  • 1
    Any of this above don't work when I try to invoke the REST api from Junit. The request comes as null. – Debaprasad Jana Mar 17 '16 at 12:10
  • This may not work in later versions of Dropwizard @DebaprasadJana - this was for Dropwizard 0.7.x – th3morg Mar 17 '16 at 12:34
  • Are there any concurrency issues with this approach? – Dragas Sep 07 '18 at 05:20
  • @Dragas every request to the application will have its own thread, so there will not be a problem with concurrency. – th3morg Sep 07 '18 at 09: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 Sep 07 '18 at 10:53
  • @Dragas I do not believe it automatically makes it a singleton. In my uses, each class is instantiated for each request. One would need to add another annotation to force it to be a singleton. Even then, I'm not sure that's possible for REST controllers. It's instance per request by default. – Andrew T Finnell Oct 16 '18 at 20:33