Jersey: Default Cache Control to no-cache

前端 未结 5 2296
孤独总比滥情好
孤独总比滥情好 2020-12-25 13:35

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

5条回答
  •  无人及你
    2020-12-25 13:46

    @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.

提交回复
热议问题