Dynamic Filter Binding

What is Dynamic Filter Binding?

Bind filters to resource methods programmatically during the app initialization time.

Components

  1. Filter
  2. DynamicFeature
  3. Resource

Filter

  • implements ContainerRequestFilter, ContainerResponseFilter
  • override filter method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class LogFilter implements ContainerRequestFilter, ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
log(reqContext.getUriInfo(), reqContext.getHeaders());

}

@Override
public void filter(ContainerRequestContext reqContext,
ContainerResponseContext resContext) throws IOException {
log(reqContext.getUriInfo(), resContext.getHeaders());


}

private void log(UriInfo uriInfo, MultivaluedMap<String, ?> headers) {
System.out.println("Path: " + uriInfo.getPath());
headers.entrySet().forEach(h -> System.out.println(h.getKey() + ": " + h.getValue()));
}
}

DynamicFeature

  • @Provider
  • implements DynamicFeature
  • override configure to register filter (only works for path ‘/order’)
  • bind filter with resource
1
2
3
4
5
6
7
8
9
10
11
12
@Provider
public class FilterRegistrationFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if (MyResource.class.isAssignableFrom(resourceInfo.getResourceClass())) {
Method method = resourceInfo.getResourceMethod();
if (method.getName().toLowerCase().contains("order")) {
context.register(new LogFilter());
}
}
}
}

Resource

Define path and verb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Path("")
public class MyResource {

@GET
@Path("customers")
public String getAllCustomers() {
System.out.println("in getAllCustomers()");
return "dummy-response for all customers";
}

@GET
@Path("customers/{id}")
public String getCustomerById(@PathParam("id") String id) {
System.out.println("in getCustomerById()");
return "dummy-response for customer " + id;
}

@GET
@Path("orders")
public String getOrders() {
System.out.println("in getOrders()");
return "dummy-response for orders";
}
}

References

https://www.logicbig.com/tutorials/java-ee-tutorial/jax-rs/filters-dynamic-binding.html