While writing a RESTful web service, I am encountering issues if I enable any sort of caching on my client (currently a .NET thick client). By default Jersey is not sending
@martin-matula's solution does not work with JAX-RS 2.0 / Jersey 2.x as ResourceFilterFactory and ResourceFilter have been removed. The solution can be adapted to JAX-RS 2.0 as follows.
Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CacheControlHeader {
String value();
}
DynamicFeature:
@Provider
public class CacheFilterFactory implements DynamicFeature {
private static final CacheResponseFilter NO_CACHE_FILTER =
new CacheResponseFilter("no-cache");
@Override
public void configure(ResourceInfo resourceInfo,
FeatureContext featureContext) {
CacheControlHeader cch = resourceInfo.getResourceMethod()
.getAnnotation(CacheControlHeader.class);
if (cch == null) {
featureContext.register(NO_CACHE_FILTER);
} else {
featureContext.register(new CacheResponseFilter(cch.value()));
}
}
private static class CacheResponseFilter implements ContainerResponseFilter {
private final String headerValue;
CacheResponseFilter(String headerValue) {
this.headerValue = headerValue;
}
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) {
// attache Cache Control header to each response
// based on the annotation value
containerResponseContext
.getHeaders()
.putSingle(HttpHeaders.CACHE_CONTROL, headerValue);
}
}
}
CacheFilterFactory needs to be registered with Jersey. I'm doing it via Dropwizard - using environment.jersey().register() - but on standalone systems I understand this can be done for example by letting Jersey scan your classes for @Provider annotations by defining the following in your web.xml:
my.package.MyApplication
org.glassfish.jersey.servlet.ServletContainer
jersey.config.server.provider.packages
my.package
See this post for more information about registering components.