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;
}