为了减少网络传输量,可以对静态资源利用gzip.exe进行压缩,然后通过response.setHeader("Content-Encoding", "gzip");设置响应头,这样浏览器就能识别压缩后的资源,正常访问。实际项目中,先对静态资源进行压缩,如.js和.css文件压缩成.gzjs和.gzcss,然后通过过滤器自动添加响应头。过滤器代码如下:
/**
* gzip压缩文件请求处理过滤器
*/
public class GzipFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
if(req instanceof HttpServletRequest) {
doFilter((HttpServletRequest)req, (HttpServletResponse)res, chain);
} else {
chain.doFilter(req, res);
}
}
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 添加响应头
response.addHeader("Content-Encoding", "gzip");
chain.doFilter(request, response);
}
}
web.xml中过滤器配置如下:
<filter>
<filter-name>GzipFilter</filter-name>
<filter-class>GzipFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.gzjs</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>*.gzcss</url-pattern>
</filter-mapping>
说明:对于其他资源也可以进行压缩处理,只需要在web.xml中添加相应的配置即可