前言
- HTTP header 中的 Cache-Control 告知客户端是否使用缓存。
- HTTP header 中的 Pragma, 最常用的是Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache- Control:no-cache相同。 Pragma: no-cache可以应用到http 1.0 和http 1.1,而Cache-Control: no-cache只能应用于http 1.1。
-
- HTTP header 中的 Expires 告知客户端响应过期的具体时间。
浏览器会有默认值
当不告知浏览器 Cache-Control 、Pragma 具体的值时,浏览器会有默认值。chrome默认是会启用缓存的。
如果不希望浏览器缓存时,则需要明确指定相关的参数值。
希望缓存一段时间:比如30分钟
Cache-Control: max-age = 1800
resp.setHeader("Cache-Control", "max-age=1800");
希望某一刻之后缓存失效:比如2020年2月7日20点0分0秒
Expires : Fri, 7 Feb 2020 20:00:00 +0800
resp.setHeader("Expires", "Fri, 7 Feb 2020 20:00:00 +0800");
时间格式标准参考:https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date expiresDate = sdf.parse("2020-02-07 20:00:00");
ZonedDateTime expiresZonedDate = ZonedDateTime.ofInstant(expiresDate.toInstant(), ZoneId.of("Asia/Shanghai"));
String expires = expiresZonedDate.format(DateTimeFormatter.RFC_1123_DATE_TIME);
时区转换:https://www.cnblogs.com/niceboat/p/7027394.html
貌似使用毫秒数也可以(缓存1分钟):
resp.setHeader("Expires", System.currentTimeMillis()+60*1000);
参考代码
@SpringBootApplication
@ServletComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@ServletComponentScan
@WebFilter(urlPatterns = {"/dashboard"},filterName = "checkLoginFilter")
public class CheckLoginFilter implements Filter {
private String loginURL = "http://app.mydomain.com/login.jsp";
private ServletContext context;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
context = filterConfig.getServletContext();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
HttpServletResponse resp = (HttpServletResponse) response;
try {
if (session.getAttribute("roleno") == null) {
resp.setDateHeader("Expires", 0);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Pragma", "no-cache");
resp.sendRedirect(loginURL);
} else {
filterChain.doFilter(request, response);
}
} catch (ServletException sx) {
context.log(sx.getMessage());
} catch (IOException iox) {
context.log(iox.getMessage());
}
}
@Override
public void destroy() {
}
}
参考
https://www.cnblogs.com/Joans/p/3956490.html
https://blog.csdn.net/u014175572/article/details/54861813
https://baijiahao.baidu.com/s?id=1612392982674092834