读取js压缩为gzjs格式文件

时间:2022-01-10 04:24:01
最近做的Ext项目Ext的插件都比较大,对于网页的浏览速度也是非常不容乐观的,于是就需要对所加载的js文件进行优化,其中一个方法就是对于较大的js文件可以进行压缩。压缩成gzjs格式,但是gzjs后缀名的文件又不能被浏览器所认识,得需要对服务器端做些处理。 

一、将js格式文件压缩成gzjs格式。使用gzip.exe打包压缩后的JS文件,最后生成xx.js.gz,把xx.js.gz文件改成xx.gzjs。压缩实例: ext-all.js (610KB), gzip.exe压缩后为ext-all.gzjs(168KB)。 
附:gzip使用方法,在命令行下输入: gzip -9 ext-all.js ext-all.js.gz 
修改ext-all.js.gz的后缀名ext-all.gzjs(注:也可以通过gzip -h命令查看帮助) 

下载地址:http://www.gzip.org 

下载地址(Windows):http://download.csdn.net/detail/mmd0308/9776749


二、在项目web.xml中加入过滤器。 

代码如下:

<filter>   
<filter-name>GzipJsFilter</filter-name>
<filter-class>net.kangsoft.util.GzipJsFilter</filter-class>
<init-param>
<param-name>headers</param-name>
<param-value>Content-Encoding=gzip</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>GzipJsFilter</filter-name>
<url-pattern>*.gzjs</url-pattern>
</filter-mapping>
三、加入过滤类。 
代码如下:

package net.kangsoft.util;  

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GzipJsFilter
implements Filter
{
Map headers = new HashMap();

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
{
request.setCharacterEncoding("UTF-8");
for (Iterator it = this.headers.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
response.addHeader((String)entry.getKey(), (String)entry.getValue());
}
chain.doFilter(request, response);
}

public void init(FilterConfig config) throws ServletException {
String headersStr = config.getInitParameter("headers");
String[] headers = headersStr.split(",");
for (int i = 0; i < headers.length; ++i) {
String[] temp = headers[i].split("=");
this.headers.put(temp[0].trim(), temp[1].trim());
}
}
}

四、在需导入js的页面head里面添加导入文件,如:<script type="text/javascript" 

src="js/ext3/ext-all.gzjs"></script> 

至此已经大功告成,在我这边测试通过,如大家在运行过程中有问题,请发信息给我。