【sprinb-boot】HttpServletResponse设置HTTP缓存
生活随笔
收集整理的這篇文章主要介紹了
【sprinb-boot】HttpServletResponse设置HTTP缓存
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
- HTTP header 中的 Cache-Control 告知客戶(hù)端是否使用緩存。
- HTTP header 中的 Pragma, 最常用的是Pragma:no-cache。在HTTP/1.1協(xié)議中,它的含義和Cache- Control:no-cache相同。 Pragma: no-cache可以應(yīng)用到http 1.0 和http 1.1,而Cache-Control: no-cache只能應(yīng)用于http 1.1。
-
- HTTP header 中的 Expires 告知客戶(hù)端響應(yīng)過(guò)期的具體時(shí)間。
瀏覽器會(huì)有默認(rèn)值
當(dāng)不告知瀏覽器 Cache-Control 、Pragma 具體的值時(shí),瀏覽器會(huì)有默認(rèn)值。chrome默認(rèn)是會(huì)啟用緩存的。
如果不希望瀏覽器緩存時(shí),則需要明確指定相關(guān)的參數(shù)值。
希望緩存一段時(shí)間:比如30分鐘
Cache-Control: max-age = 1800 resp.setHeader("Cache-Control", "max-age=1800");希望某一刻之后緩存失效:比如2020年2月7日20點(diǎn)0分0秒
Expires : Fri, 7 Feb 2020 20:00:00 +0800 resp.setHeader("Expires", "Fri, 7 Feb 2020 20:00:00 +0800");時(shí)間格式標(biāo)準(zhǔn)參考: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);時(shí)區(qū)轉(zhuǎn)換:https://www.cnblogs.com/niceboat/p/7027394.html
貌似使用毫秒數(shù)也可以(緩存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
總結(jié)
以上是生活随笔為你收集整理的【sprinb-boot】HttpServletResponse设置HTTP缓存的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 消息称亚马逊正为 Fire TV、Ech
- 下一篇: 百度CarLife导航怎么查找去附近银行