HTTP头信息学习

本贴用于记录HTTP头信息。

 

Last-Modified和If-Modified-Since

     它们都是用来记录页面最后修改时间的头信息,只是:Last-Modified : 是服务器发送给客户端的头信息,而If-Modified-Since是从客户端发送给服务器的。在上一次服务器端发送回来的响应中,包含请求页面最后一次修改(Last Modified)的时间戳。浏览器缓存此页面,当相同的GET请求又再一次发起时,浏览器会把Last-Modified时间戳包含在If-Modified-Since字段中发送给服务器,等待服务器验证缓存在客户端的页面是否是最新的,如果客户端页面不是最新的,就发回新的页面。如果页面是最新的,就返回304状态码告诉客户端其缓存的页面是最新的,之后客户端会加载缓存中的页面,这样在网络发送的数据就大大减少,减轻了服务器端的负担。

     Tomcat在实现HttpServlet的services方法,就体现了上述过程。

servlet源代码
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 {
//其中HEADER_IFMODSINCE = "If-Modified-Since"
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 {
//返回304状态码
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}

 

posted on 2010-07-20 12:24  joolu  阅读(571)  评论(4编辑  收藏  举报