美文网首页java
tomcat直接设置Response的Headers

tomcat直接设置Response的Headers

作者: 岁月静好忄 | 来源:发表于2019-05-22 09:32 被阅读0次

在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包

image.png
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

相关文章

网友评论

    本文标题:tomcat直接设置Response的Headers

    本文链接:https://www.haomeiwen.com/subject/jmzezqtx.html