Spring3.0中的对页面的Etag支持,基于的MD5的生成,非常好,可移植到Spring2.5上
Support for ETags is provided by the servlet filter ShallowEtagHeaderFilter. It is a plain Servlet
Filter, and thus can be used in combination with any web framework. The
ShallowEtagHeaderFilter filter creates so-called shallow ETags (as opposed to deep ETags,
more about that later).The filter caches the content of the rendered JSP (or other content), generates an
MD5 hash over that, and returns that as an ETag header in the response. The next time a client sends a
request for the same resource, it uses that hash as the If-None-Match value. The filter detects this,
renders the view again, and compares the two hashes. If they are equal, a 304 is returned. This filter will
not save processing power, as the view is still rendered. The only thing it saves is bandwidth, as the
rendered response is not sent back over the wire.
Support for ETags is provided by the servlet filter ShallowEtagHeaderFilter. It is a plain Servlet
Filter, and thus can be used in combination with any web framework. The
ShallowEtagHeaderFilter filter creates so-called shallow ETags (as opposed to deep ETags,
more about that later).The filter caches the content of the rendered JSP (or other content), generates an
MD5 hash over that, and returns that as an ETag header in the response. The next time a client sends a
request for the same resource, it uses that hash as the If-None-Match value. The filter detects this,
renders the view again, and compares the two hashes. If they are equal, a 304 is returned. This filter will
not save processing power, as the view is still rendered. The only thing it saves is bandwidth, as the
rendered response is not sent back over the wire.
<filter>
<filter-name>etagFilter</filter-name>
<filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>etagFilter</filter-name>
<servlet-name>petclinic</servlet-name>
</filter-mapping> ShallowEtagResponseWrapper responseWrapper = new ShallowEtagResponseWrapper(response);
filterChain.doFilter(request, responseWrapper);
byte[] body = responseWrapper.toByteArray();
String responseETag = generateETagHeaderValue(body);
response.setHeader(HEADER_ETAG, responseETag);
String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
if (responseETag.equals(requestETag)) {
if (logger.isTraceEnabled()) {
logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
}
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
else {
if (logger.isTraceEnabled()) {
logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag +
"], sending normal response");
}
response.setContentLength(body.length);
FileCopyUtils.copy(body, response.getOutputStream());
}
本文介绍Spring3.0中ShallowEtagHeaderFilter过滤器如何通过缓存JSP内容并生成MD5散列来实现Etag支持,节省带宽消耗。当客户端请求相同资源时,若散列值未变更,则返回304状态。
1462

被折叠的 条评论
为什么被折叠?



