如何在dropwizard中为静态资源启用缓存控制

时间:2016-07-05 11:02:32

标签: java caching filter browser-cache dropwizard

我正在尝试启用缓存但仍无法正常工作。没有设置响应标头。

配置静态资产。 在yml中:

assets: 
  overrides:
     /sale/images/: /tmp/deals/images/

以下是我用于启用缓存的代码,

  import java.io.IOException;
        import java.util.Date;

        import javax.servlet.Filter;
        import javax.servlet.FilterChain;
        import javax.servlet.FilterConfig;
        import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.http.HttpServletResponse;

        public class CacheControlFilter implements Filter {

            public void doFilter(ServletRequest request, ServletResponse response,

                    FilterChain chain) throws IOException, ServletException {

                HttpServletResponse resp = (HttpServletResponse) response;

                // Add whatever headers you want here

                resp.setHeader("Cache-Control", "pubic, max-age=100000");

                resp.setHeader("Expires", new Date().getTime() + 500000 + "");
                resp.setContentType("image/*");
                chain.doFilter(request, response);

            }

            public void destroy() {
            }

            public void init(FilterConfig arg0) throws ServletException {
            }

        }

在Application类中,将其包含在run方法中,

 environment.servlets().addFilter("/sale/images/", new CacheControlFilter()).
            addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

如果有人知道,请帮我解决这个问题。

0 个答案:

没有答案