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

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

The filter

public class FilteringFilter implements ContainerRequestFilter,
        ContainerResponseFilter {
        public void filter(ContainerRequestContext requestContext) throws IOException {

        public void filter(ContainerRequestContext requestContext,
                           ContainerResponseContext responseContext) throws IOException {

The filtered method

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