欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【sprinb-boot】HttpServletResponse设置HTTP缓存

发布时间:2024/9/19 编程问答 57 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【sprinb-boot】HttpServletResponse设置HTTP缓存 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

前言

  • 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;@Overridepublic void init(FilterConfig filterConfig) throws ServletException {context = filterConfig.getServletContext();}@Overridepublic 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());}}@Overridepublic 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

总结

以上是生活随笔为你收集整理的【sprinb-boot】HttpServletResponse设置HTTP缓存的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。