首页 > 代码库 > Tomcat配置gzip压缩
Tomcat配置gzip压缩
一 对于Tomcat5.0以后的版本号是支持对输出内容进行压缩的. 使用的是gzip压缩格式
下 面是tomcat5.5.20 中的$tomcat_home$/conf/server.xml的原内容 1 < Connector port ="80" maxHttpHeaderSize ="8192"
maxThreads ="150" minSpareThreads ="25" maxSpareThreads ="75"
enableLookups ="false" redirectPort ="8443" acceptCount ="100"
connectionTimeout ="20000" disableUploadTimeout ="true" URIEncoding ="utf-8" />
<!-- Note : To disable connection timeouts, set connectionTimeout value
to 0 -->
<!-- Note : To use gzip compression you could set the following properties :
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
-->从上面的第 8行内容能够看出,要使用gzip压缩功能,你能够在Connector实例中加上例如以下 属性就可以
2) compressionMinSize="2048" 启用压缩的输出内容大小,这里面默觉得2KB
3) noCompressionUserAgents="gozilla, traviata" 对于下面的浏览器,不启用压缩
4) compressableMimeType="text/html,text/xml" 压缩类型(默觉得text/html,text/xml,text/plain)
我 这里的配置内容为:
<Connector port="80" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="utf-8"
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain" />
<!-- Note : To disable connection timeouts, set connectionTimeout value
to 0 -->
<!-- Note : To use gzip compression you could set the following properties :
compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml"
-->
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
public class HttpTester {
public static void main(String[] args) throws Exception{
HttpClient http = new HttpClient();
GetMethod get = new GetMethod("http://www.dlog.cn/js/prototype.js");
try{
get.addRequestHeader("accept-encoding", "gzip,deflate");
get.addRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");
int er = http.executeMethod(get);
if(er==200){
System.out.println(get.getResponseContentLength());
String html = get.getResponseBodyAsString();
System.out.println(html);
System.out.println(html.getBytes().length);
}
}finally{
get.releaseConnection();
}
}
}
运行这个測试程序,看看它所输出的是什么内容,假设输出的是一些 乱码,以及打印内容的长度远小于实际的长度,那么恭喜你,你的配置生效了,你会发现你站点的浏览速度比曾经快多了。
Tomcat配置gzip压缩