请求头中的Last-Modified 和 Is-Modified-Since
2016年8月8日 星期一
拖了好几天,哎。
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 / 1000 * 1000)) { // 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); } } } else if (method.equals(METHOD_HEAD)) { long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { // // Note that this means NO servlet supports whatever // method was requested, anywhere on this server. // String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
在看Servlet源码的时候,发现没有直接调用doGet()方法,而且先判断了一下getLastModified()获取的值,
稍微调查了一下,这个是和浏览器缓存有关的,或者说是一种优化措施。
当我们第一次请求一个地址的时候,如下图,

如果能够访问,他会返回一个200代表访问成功,此时应答头信息中会有一个 Last-Modified 代表服务器这个文件的最后修改时间。
当我们再次请求的时候,如下图

如果请求过了,就会在请求头,有一个If-Modified-Since的值,这时候传到服务器,服务器就会拿这个值和上次修改的时间对比,如果小于上次修改的时间,说明服务器上的文件被修改过,就再次从服务器进行下载,返回200
如果没有修改就像上图一样,返回一个304,代表客户端已经执行了GET,但文件未变化。

浙公网安备 33010602011771号