java

tomcat直接设置Response的Headers

2019-05-22  本文已影响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

上一篇 下一篇

猜你喜欢

热点阅读