读取js压缩gzjs格式文件,读取失败

今天在做以Ext3.4的基础的JS项目,但是Ext插件比较大,这样一来浏览速度就变慢,就把JS文件压缩为gzjs,但是gzjs浏览不能识别,需要一定服务端的处理。

处理步骤如下:

1、将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

 

2、在项目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>


 

3、加入过滤类。

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());
    }
}
}


4、在需导入js的页面head里面添加导入文件,如:<script type="text/javascript"
src="js/ext3/ext-all.gzjs"></script>

参考:http://kangsoft.iteye.com/blog/602731

你可能感兴趣的:(String,HashMap,filter,ext,iterator,Class)