tomcat直接设置Response的Headers

tomcat直接设置Response的Headers
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说tomcat直接设置Response的Headers,希望能够帮助大家进步!!!

在tomcat中直接设置Response的Headers
比如:设置Cache-Control

1、编写过滤器

 

package com.vking.power.web.filter;

import java.io.IOException;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 过滤器
*/
public class StaticCacheControl implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;   
        response.setHeader("Cache-Control", "max-age=2592000");
        chain.doFilter(request, response);
    }
    public void init(FilterConfig filterConfig) throws ServletException {}
    
    public void destroy() {}

}

2、将StaticCacheControl导出为jar包

tomcat直接设置Response的Headers

image.png

 

tomcat直接设置Response的Headers

image.png

3、将jar包直接扔到tomcat/lib目录下

4、在tomcat/conf/web.xml中增加下列代码

 

    <filter>
        <filter-name>staticFilter</filter-name>
        <!--包名加文件名-->
        <filter-class>com.vking.power.web.filter.StaticCacheControl</filter-class>
    </filter>
     
    <filter-mapping>
        <filter-name>staticFilter</filter-name>
        <!--需要过滤的地址-->
        <url-pattern>*.pak</url-pattern>
    </filter-mapping>

5、重启tomcat

作者:岁月静好忄
链接:https://www.jianshu.com/p/5cc7d87c19f0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18155

发表评论