How to set Expires HTTP header on a single JS file in Apache Tomcat?

前端 未结 2 1419
梦谈多话
梦谈多话 2020-12-14 14:06

I have a js file which is cached between 5-10 minutes, depending on whether I\'m using tomcat from the eclipse (via GWT plugin) or starting tomcat as standalone

2条回答
  •  感情败类
    2020-12-14 14:35

    Using a javax.servlet.Filter

    One way to do this in a portable way (across different app servers), is using Filters. In your web.xml add the following:

      
        headersFilter
        MyHeadersFilter
      
      
        headersFilter
        /*
      
    

    Then implement your MyHeadersFilter like:

    public class MyHeadersFilter implements Filter {
    
      @Override
      public void doFilter(final ServletRequest request,
             final ServletResponse response, final FilterChain chain)
             throws IOException, ServletException {
    
          final HttpServletRequest httpRequest = (HttpServletRequest) request;
          final String requestUri = httpRequest.getRequestURI();
    
          final HttpServletResponse httpResponse = (HttpServletResponse) response;
    
    
          if (requestUri.contains(".nocache.")) {
            httpResponse.addHeader("Cache-Control", "no-cache");
            ...
    
          } else if (...) {
            ...
          }
    
          chain.doFilter(request, response);
      }
    }
    

    Optional: Configurable Filters

    You can also make your filter configurable from your web.xml, by using s:

      
        headersFilter
        MyHeadersFilter
        
            myParam
            myValue
        
      
    

    Add the following to MyHeadersFilter:

        private FilterConfig filterConfig;
    
        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
        }
    
        @Override
        public void destroy() {
            this.filterConfig = null;
        }
    

    That makes it possible to access your init-param(s) using:

    filterConfig.getInitParameter("myParam")
    

提交回复
热议问题