java 配置Apache,Tomcat的gzip压缩功能
2) compressionMinSize="2048" 启用压缩的输出内容大小,这里面默认为2KB
3) noCompressionUserAgents="gozilla, traviata" 对于以下的浏览器,不启用压缩?
4) compressableMimeType="text/html,text/xml" 压缩类型
我 这里的配置内容为:
?1????<Connector?port="80"?maxHttpHeaderSize="8192"
?2?????????????? maxThreads="150"?minSpareThreads="25"?maxSpareThreads="75"
?3?????????????? enableLookups="false"?redirectPort="8443"?acceptCount="100"
?4?????????????? connectionTimeout="20000"?disableUploadTimeout="true"?URIEncoding="utf-8"
?5????????????????? compression="on"?
?6?????????????? compressionMinSize="2048"?
?7?????????????? noCompressionUserAgents="gozilla,?traviata"?
?8?????????????? compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain"??/>
?9??? <!--?Note?:?To?disable?connection?timeouts,?set?connectionTimeout?value
10???? to?0?-->
11???
12??? <!--?Note?:?To?use?gzip?compression?you?could?set?the?following?properties?:
13???
14?????????????? compression="on"?
15?????????????? compressionMinSize="2048"?
16?????????????? noCompressionUserAgents="gozilla,?traviata"?
17?????????????? compressableMimeType="text/html,text/xml"
18??? -->
19
一旦启用了这个压缩功能后,我们怎么来测试压缩是否有效呢?首先Tomcat是根据浏览器请求头中的accept-encoding来判断浏览器是否支持压缩功能,如果这个值包含有gzip,就表明浏览器支持gzip压缩内容的浏览,所以我们可以用httpclient来写一个这样的简单测试程序
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();
}
}
}
执行这个测试程序,看看它所输出的是什么内容,如果输出的是一些乱码,以及打印内容的长度远小于实际的长度,那么恭喜你,你的配置生效了,你会发现你网站的浏览速度比以前快多了。
<filter> <filter-name>AddHeaderFilter</filter-name> <filter-class> badqiu.web.filter.AddHeaderFilter </filter-class> <init-param> <param-name>headers</param-name> <param-value>Content-Encoding=gzip</param-value> </init-param> </filter> <filter-mapping> <filter-name>AddHeaderFilter</filter-name> <url-pattern>*.gzjs</url-pattern> </filter-mapping>
<html><head><!-- type="text/javascript"不可少,有些浏览器缺少这个不能运行,具体已经忘记了 --><script src="prototype.gzjs" type="text/javascript"></script></head><body> <input id="username" name="username" value="badqiu"/><br /> <input id="email" value="badqiu@gmail.com"/><script> <!-- 测试prototype的方法是否正常--> alert($F('username'))</script></body></html>