如何在Tomcat 7中将缓存控制设置为无缓存?

sbtkgmzw  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(551)

我正在尝试将Tomcat 7的Cache Control设置为no-cache选项。
我尝试在我的web.xml中使用ExpiresFilter,如下所示:

<filter>
    <filter-name>ExpiresFilter</filter-name>
    <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
    <init-param>
    <param-name>ExpiresByType image</param-name>
    <param-value>access plus 0 seconds</param-value>
    </init-param>
    <init-param>
    <param-name>ExpiresByType text/css</param-name>
    <param-value>access plus 0 seconds</param-value>
    </init-param>
    <init-param>
    <param-name>ExpiresByType application/javascript</param-name>
    <param-value>access plus 0 seconds</param-value>
    </init-param>

    <init-param>
    <param-name>ExpiresDefault</param-name>
    <param-value>access plus 0 seconds</param-value>
    </init-param>
</filter>

<filter-mapping>
<filter-name>ExpiresFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

然而,当我阅读我的响应头时,我得到的是:
Cache-Control:max-age=0
而不是Cache-Control: no-cache
如何将Tomcat服务器设置为仅通过配置文件指定Cache-Control: no-cache

vhmi4jdf

vhmi4jdf1#

要设置“缓存控制:no-cache'你将不得不创建一个自定义过滤器,ExpiresFilter用于添加'Expires'和'Cache-Control:max-age='根据其'Content-Type'将HTTP响应的头发送到HTTP响应,并且不会帮助设置'no-cache'
请按照以下步骤操作
1.应该编写一个自定义过滤器来设置头文件,将过滤器打包到一个.jar中
1.将.jar文件放入$ Catalina _HOME/lib
1.验证在$ Catalina _HOME/lib中添加jar后是否没有“ClassNotFoundException”

package nocache;
    
    import javax.servlet.Filter;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    
    public class CacheFilter implements Filter { 
    
        @Override 
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
                             FilterChain filterChain) throws IOException, ServletException { 
    
            HttpServletResponse response = (HttpServletResponse) servletResponse; 
            response.setHeader("Cache-Control", "no-cache"); 
            filterChain.doFilter(servletRequest, response); 
        } 
    }

1.将以下内容添加到$ Catalina _HOME/conf/web.xml文件中
web.xml部署描述符代码段示例

<filter>
        <filter-name>CacheFilter</filter-name>
        <filter-class>nocache.CacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CacheFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

1.访问应用程序并检出响应头。

相关问题