HttpServlet中提供了实现浏览器和服务器缓存的模版方法service

HttpServlet的service方法中提供了实现缓存的模版

protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        String method = req.getMethod();

        if (method.equals(METHOD_GET)) {
            long lastModified = getLastModified(req);
            if (lastModified == -1) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                if (ifModifiedSince < lastModified) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

1、get请求时先判断lastModified(现在的版本号)是否大于ifModifiedSince(请求头中的版本号)

if (ifModifiedSince < lastModified) 

2、如果满足条件才回去调用doGet,且把最新的版本号放入Response中

maybeSetLastModified(resp, lastModified);
doGet(req, resp);

3、如果不满足,ifModifiedSince = lastModified说明请求头中的版本号已经是最新版本。返回304

//SC_NOT_MODIFIED = 304
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

4、HttpServlet中的getLastModified方法默认返回-1,即每次都调用doGet,实现缓存我们可以覆盖getLastModified方法返回正确的版本号。

protected long getLastModified(HttpServletRequest req) {
        return -1;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值