Reputation: 1333
I am writing a REST service using jersey 2 and servlet 3. I have custom GET methods, all of which first look if the request has certain headers. If headers are not present, I am throwing an exception. Is there a way to provide a "parent-like" @GET method, which would reject requests withouth certain headers before they proceed to a corresponding @Path-link? Like, if my service has a name myService, and the @Path is "getHello", how to check for the headers first before going to myService/getHello annotated method?
Upvotes: 1
Views: 139
Reputation: 209112
You can use a ContainerRequestFilter
and check the method
@Provider
public class CheckHeaderFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext context) {
if (context.getMethod().toUpperCase().equals("GET")) {
String header = context.getHeaderString("SomeHeader");
MultivaluedMap<String, String> headers = context.getHeaders();
if(notValidHEaders) {
context.abortWith(Response.status(400).entity("Bad").build());
// or throw WebApplicationException
}
}
}
}
If you are using package scanning to register resources, the filter should also get picked up and registered because of the @Provider
annotation. Otherwise, you will need to register it yourself
See also:
Upvotes: 1