欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Tomcat7启用gzip压缩 博客分类: Web&App Server tomcatgzip压缩javascriptjs 

程序员文章站 2024-03-18 20:42:04
...
背景:HTTP 压缩可以大大提高浏览网站的速度,它的原理是,在客户端请求网页后,从服务器端将网页文件压缩,再下载到客户端,由客户端的浏览器负责解压缩并浏览。相对于普通的浏览过程HTML ,CSS,Javascript , Text ,它可以节省40%左右的流量。更为重要的是,它可以对动态生成的,包括CGI、PHP , JSP , ASP , Servlet,SHTML等输出的网页也能进行压缩,压缩效率惊人。

第一步:修改$tomcat_home$/conf/server.xml

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
修改为
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1"   redirectPort="8443"         
     compression="on"
         compressionMinSize="2048"
         noCompressionUserAgents="gozilla, traviata"
         compressableMimeType="text/html,text/xml,text/plain,text/css,
         text/javascript,text/json,application/x-javascript,
         application/javascript,application/json"/>
注意要添加application/javascript,tomcat5用的可能是text/javascript,但tomcat7用的是application/javascript

第二步:用浏览器访问你重新部署的程序,打开开发者工具,进入Network面板,刷新页面,然后选择一个js文件点击,查看 Headers下面的Response Headers,里面会标明Encoding为gzip,那么恭喜你成功了。

以上是服务器自动帮你压缩文件,但如果文件比较大,你希望提前压缩后,到时候服务器自动读取你压缩的gzip文件而不是由服务器来压缩,怎么做呢?
第一步:实现filter类,让filter类来读取你压缩的gzip文件
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GzipFilter implements Filter {

	private ServletContext ctx;
	private Logger logger = Logger.getLogger(GzipFilter.class.getName());
	private String contextPath;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		String accept = req.getHeader("Accept-Encoding");
		InputStream in = null;
		contextPath = ctx.getContextPath();
		uri = uri.substring(contextPath.length());
		if (accept != null && accept.contains("gzip") && (in = ctx.getResourceAsStream(uri + ".gz")) != null) {
			logger.info("start getting gzip file "+uri);
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] b = new byte[1024 * 8];
			int read = 0;
			while ((read = in.read(b)) >= 0) {
				bout.write(b, 0, read);
			}
			in.close();

			res.setHeader("Content-Encoding", "gzip");
			res.setContentType("application/javascript;charset=UTF-8");
			res.setContentLength(bout.size());

			ServletOutputStream out = res.getOutputStream();
			out.write(bout.toByteArray());
			out.flush();
			logger.info("finish getting gzip file "+uri);
			return;
		} else {   
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		ctx = config.getServletContext();
	}

}



第二步:配置web.xml
添加如下片段即可
	<!-- read the precompressed gzip js file-->
	<filter>
		<filter-name>gzip</filter-name>
		<filter-class>GzipFilter</filter-class>
	</filter>
 
	<filter-mapping>
		<filter-name>gzip</filter-name>
		<url-pattern>*.js</url-pattern>
	</filter-mapping>

第三步:压缩你的js文件,比如a.js为a.js.gzip文件
第四步:用chrome验证是否成功