HTTP缓存SpringMVC实现

@RequestMapping("/cache")
    public ResponseEntity<String> cache(
            HttpServletRequest request,
            //为了方便测试,此处传入文档最后修改时间
            @RequestParam("millis") long lastModifiedMillis,
            //浏览器验证文档内容是否修改时传入的Last-Modified
            @RequestHeader(value = "If-Modified-Since", required = false) Date ifModifiedSince) {

        //当前系统时间
        long now = System.currentTimeMillis();
        //文档可以在浏览器端/proxy上缓存多久
        long maxAge = 20;

        //判断内容是否修改了,此处使用等值判断
        if(ifModifiedSince != null && ifModifiedSince.getTime() == lastModifiedMillis) {
            return new ResponseEntity<String>(HttpStatus.NOT_MODIFIED);
        }

        DateFormat gmtDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);

        String body = "<a href=''>点击访问当前链接</a>";
        MultiValueMap<String, String> headers = new HttpHeaders();

        //文档修改时间
        headers.add("Last-Modified", gmtDateFormat.format(new Date(lastModifiedMillis)));

        //当前系统时间
        headers.add("Date", gmtDateFormat.format(new Date(now)));
        //过期时间 http 1.0支持
        headers.add("Expires", gmtDateFormat.format(new Date(now + maxAge)));
        //文档生存时间 http 1.1支持
        headers.add("Cache-Control", "max-age=" + maxAge);
        return new ResponseEntity<String>(body, headers, HttpStatus.OK);
    }
   
 @RequestMapping("/cache/etag")
    public ResponseEntity<String> cache(
            HttpServletRequest request,
            HttpServletResponse response,
            //浏览器验证文档内容的实体 If-None-Match
            @RequestHeader (value = "If-None-Match", required = false) String ifNoneMatch) {

        //当前系统时间
        long now = System.currentTimeMillis();
        //文档可以在浏览器端/proxy上缓存多久
        long maxAge = 10;

        String body = "<a href=''>点击访问当前链接</a>";

        //弱实体
        String etag = "W/\"" + md5(body) + "\"";

        if(StringUtils.equals(ifNoneMatch, etag)) {
            return new ResponseEntity<String>(HttpStatus.NOT_MODIFIED);
        }

        DateFormat gmtDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        MultiValueMap<String, String> headers = new HttpHeaders();

        //ETag http 1.1支持
        headers.add("ETag", etag);
        //当前系统时间
        headers.add("Date", gmtDateFormat.format(new Date(now)));
        //文档生存时间 http 1.1支持
        headers.add("Cache-Control", "max-age=" + maxAge);
        return new ResponseEntity<String>(body, headers, HttpStatus.OK);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值