gzip压缩js和html文件java源码
作者:张颋 版本:V1.0 最后更新日期:2013/4/25 http://idata.blog.51cto.com
静态文件压缩是十年前的技术,在视频、图片占据带宽主流的今天对很多网站已不再重要。但是,对于数据服务而言,静态文件压缩技术依然可以摆在显著位置值得一提,甚至可以说比十年前更加重要了。究其原因根本上是因为javascript和html5。在数据服务领域,笔者相信基于javascript+html5的数据可视化技术会成为未来的主流,这正是压缩技术的用武之地。
引入第三方jar包实现压缩是可行的,但是这是以牺牲灵活性和简单性为代价的。在技术进步竞争激烈的今天,关键技术成为黑盒就好比与人赛跑的您身上又多了一道枷锁。下面的代码已在生产环境证实可行,期待您的反馈:
web.xml
- <!-- ResponseFilter must be executed as the last one of the filter chain.-->
- <filter>
- <filter-name>ResponseFilter</filter-name>
- <filter-class>com.datawebservice.ResponseFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>ResponseFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
ResponseFilter.java
- package com.datawebservice;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.util.zip.GZIPOutputStream;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ResponseFilter implements Filter {
- public void init(FilterConfig filterConfig) throws ServletException {}
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain filterChain) throws IOException, ServletException {
- HttpServletRequest httpServletRequest = (HttpServletRequest) request;
- HttpServletResponse httpServletResponse = (HttpServletResponse) response;
- String requestURI = httpServletRequest.getRequestURI();
- if (requestURI.endsWith("html")|| requestURI.endsWith("js"))
- {
- ResponseWrapper wrapper = new ResponseWrapper(httpServletResponse);
- filterChain.doFilter(request, wrapper);
- String resultText = wrapper.getResultText();
- wrapper.close();
- //压缩
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- GZIPOutputStream gzip = new GZIPOutputStream(os);
- gzip.write(resultText.getBytes("UTF-8"));
- gzip.close();
- //输出
- byte[] bytes = os.toByteArray();
- httpServletResponse.setContentType("text/html; charset=UTF-8");
- httpServletResponse.addHeader("Content-Length",Integer.toString(bytes.length));
- httpServletResponse.addHeader("Content-Encoding", "gzip");
- ServletOutputStream output = httpServletResponse.getOutputStream();
- output.write(bytes);
- output.flush();
- output.close();
- }else {
- filterChain.doFilter(httpServletRequest, httpServletResponse);
- }
- }
- public void destroy() {}
- }
ResponseWrapper.java
- package com.datawebservice;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.io.Writer;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper;
- public class ResponseWrapper extends HttpServletResponseWrapper {
- private String responseText="";
- private ByteArrayOutputStream responseStream=null;
- public ResponseWrapper(HttpServletResponse response) {
- super(response);
- responseStream = new ByteArrayOutputStream();
- }
- public String getResultText() {
- if(responseText.equals("")){
- try{
- responseText= new String(responseStream.toByteArray(),"UTF-8");
- }catch(Exception e){
- System.out.println("getResultText exception");
- System.out.println(e.getMessage());
- }
- }
- return responseText;
- }
- public byte[] getStreamBytes() {
- return responseStream.toByteArray();
- }
- public void close(){
- try{
- responseStream.close();
- }catch(Exception e){
- System.out.println("ResponseWrapper.responseStream.close() throw exception");
- System.out.println(e.getMessage());
- }
- }
- public ServletOutputStream getOutputStream() throws IOException {
- return (new MyServletOutputStream());
- }
- public PrintWriter getWriter() throws IOException {
- return (new MyPrintWriter(new PrintWriter(new MyServletOutputStream())));
- }
- class MyServletOutputStream extends ServletOutputStream{
- MyServletOutputStream(){
- }
- public void close() throws IOException {
- super.close();
- }
- public void flush() throws IOException {
- super.flush();
- }
- public void write(int b) throws IOException {
- write((byte)b);
- }
- public void write(byte b[]) throws IOException {
- write(b, 0, b.length);
- }
- public void write(byte b[], int off, int len) throws IOException {
- responseStream.write(b, off, len);
- }//end write
- }//end class MyServletOutputStream
- class MyPrintWriter extends PrintWriter{
- MyPrintWriter(Writer out){
- super(out);
- }
- public void flush(){
- }
- public void close(){
- }
- public void write(int b) {
- char[] cb = new char[1];
- cb[0]=(char)b;
- write(cb);
- }
- public void write(char[] chars) {
- write(chars,0,chars.length);
- }
- public void write(String s){
- responseText=responseText+s;
- }
- public void write(char buf[],int off,int len){
- responseText=responseText+String.copyValueOf(buf, off, len);
- }
- public void write(String s,int off,int len){
- responseText=responseText+s.substring(off, off+len);
- }
- }
- }
补充说明:我使用了内部类来简化代码。如果您不乏冒险精神,这份代码也可用于压缩jsp。
本文转自 hexiaini235 51CTO博客,原文链接:http://blog.51cto.com/idata/1186176,如需转载请自行联系原作者