Reputation: 2085
Is there any way to get the request (HttpServletRequest?) programmatically? I can only find how to do it with an annotation on the endpoint method/class.
Per https://stackoverflow.com/a/5118844/190164 I can add an annotated argument to my endpoint:
@POST
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public String showTime(
@Context HttpServletRequest httpRequest
) {
// The method body
}
Or I can injected in the class(https://stackoverflow.com/a/26181971/190164)
public class MyResource {
@Context
private HttpServletRequest httpRequest;
@GET
public Response foo() {
httpRequest.getContentType(); //or whatever else you want to do with it
}
}
however I would like access to the request in another class that isn't directly linked to Jersey. Adding the @Context injection like in the second example above doesn't work, as the class isn't instantiated by Jersey. I'd like to be able to do something like
HttpServletRequest.getCurrentRequest()
but I haven't been able to find any static method somewhere.
Upvotes: 1
Views: 2076
Reputation: 426
If you are looking for some security solutions you can use servlet filters (create class that implements Filter
) or you can implement ContainerRequestFilter
and by overriding filter
you can perform your filtering .Outside filters The context elements are always only accessible in the controller (where you place the path annotations) , there is no way to access this type of content from outside the controller other than passing it to the method or Object desired:
@Context
private HttpServletRequest httpRequest;
@GET
public Response foo() {
someMethod(httpRequest); //or whatever else you want to do with it
}
}
hope this helps.
Upvotes: 1