magic_turtle
magic_turtle

Reputation: 1333

Java Rest how to make an overall get filter

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

Answers (1)

Paul Samsotha
Paul Samsotha

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

Related Questions