October 15, 2015

Today, I learned:
How to scope Filters for JAX-RS services

If you want to write a JAX-RS filter that only applies to methods that are given a specific annotation, you can use the @NameBinding annotation for static binding of filters to methods. For example you could create a FilteringFilter that you only want to apply to methods annotated with @Filtered.

Note: if you separate your implementation from your interface then you will need to apply the annotation to the interface, not the implementation.

The details

To do this you would want to create the annotation and the filter, as follows:

The annotation

@NameBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Filtered { }

The filter

@Provider
@Filtered
public class FilteringFilter implements ContainerRequestFilter,
        ContainerResponseFilter {
        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
                System.out.println("BEFORE");
        }

        @Override
        public void filter(ContainerRequestContext requestContext,
                           ContainerResponseContext responseContext) throws IOException {
                System.out.println("AFTER");
        }
}

The filtered method

class ServiceApi {
  @GET
  @Logged
  String getName(@PathParam("userId") String userId);
}
Filed under: