30

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

I just found out

@Context Request request;
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
qnoid
  • 2,346
  • 2
  • 26
  • 45

2 Answers2

67

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

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

 }

Optionally you can also inject:

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
dfa
  • 114,442
  • 31
  • 189
  • 228
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
  }
}
Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
th3morg
  • 4,321
  • 1
  • 32
  • 45
  • 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