Jersey: Default Cache Control to no-cache

前端 未结 5 2240
孤独总比滥情好
孤独总比滥情好 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:45

    This is easy with Jersey by using a ResourceFilterFactory - you can create any custom annotation you attach to your methods to set cache control settings. ResourceFilterFactories get called for each discovered resource method when the application initializes - in your ResourceFilterFactory you can check if the method has your @CacheControlHeader annotation (or whatever you want to call it) - if not, simply return response filter that adds "no-cache" directive to the response, otherwise it should use the settings from the annotation. Here is an example of how to do that:

    public class CacheFilterFactory implements ResourceFilterFactory {
        private static final List NO_CACHE_FILTER = Collections.singletonList(new CacheResponseFilter("no-cache"));
    
        @Override
        public List create(AbstractMethod am) {
            CacheControlHeader cch = am.getAnnotation(CacheControlHeader.class);
            if (cch == null) {
                return NO_CACHE_FILTER;
            } else {
                return Collections.singletonList(new CacheResponseFilter(cch.value()));
            }
        }
    
        private static class CacheResponseFilter implements ResourceFilter, ContainerResponseFilter {
            private final String headerValue;
    
            CacheResponseFilter(String headerValue) {
                this.headerValue = headerValue;
            }
    
            @Override
            public ContainerRequestFilter getRequestFilter() {
                return null;
            }
    
            @Override
            public ContainerResponseFilter getResponseFilter() {
                return this;
            }
    
            @Override
            public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
                // attache Cache Control header to each response based on the annotation value
                response.getHttpHeaders().putSingle(HttpHeaders.CACHE_CONTROL, headerValue);
                return response;
            }
        }
    }
    

    The annotation can look like this:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface CacheControlHeader {
        String value();
    }
    

    The ResourceFilterFactory can be registered in your application by adding the following init param to the definition of Jersey servlet in web.xml:

    
        com.sun.jersey.spi.container.ResourceFilters
        package.name.CacheFilterFactory
    
    

提交回复
热议问题