目的:当项目资源文件越来越大,提升请求效率就越发迫切,为了提高浏览器响应速度
1.配置 只需在Tomcat的conf下的 server.xml配置就行了 在tomcat你访问的端口下配置
1. <Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
compression="on"
compressionMinSize="50" n
oCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,application/javascript,text/css"/>
分别对应
- compression="on" 打开压缩功能
- compressionMinSize="50" 启用压缩的输出内容大小,默认为2KB
- noCompressionUserAgents="gozilla, traviata" 对于以下的浏览器,不启用压缩
- compressableMimeType="text/html,text/xml,application/javascript,text/css" 哪些资源类型需要压缩
2.测试是否配置成功
第一种是直接通过浏览器访问资源 在响应头中发现 Content-Encoding:gzip 则开启成功
1已经配置gzip的
2未配置gzip的
第二种是通过自定义测试方法httpClien发送请求访问资源 配置了的会返回乱码以及大小为为配置压缩的40%左右
1.所需依赖包
commons-httpclient-3.1.jar commons-codec-1.11.jar
2测试代码
public static void main(String[] args) throws Exception{
HttpClient http = new HttpClient();
GetMethod get = new GetMethod("http://localhost:8081/Spring-MVC-model/index.badbaa95.js");
try{
//设置请求头
get.addRequestHeader("accept-encoding", "gzip,deflate");
get.setRequestHeader("Connection", "close");
get.addRequestHeader("user-agent", "Mozilla/5.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();
}
}
配置gzip压缩打印对比
1.已经配置gzip的
2.未配置gzip的