tomcat gzip 网页压缩技术

192 篇文章 0 订阅
 gzip是http协议中使用的一种加密算法,客户端向web服务器端发出了请求后,通常情况下服务器端会将页面文件和其他资源,返回到客户端,客户端加载后渲染呈现,这种情况文件一般都比较大,如果开启Gzip ,那么服务器端响应后,会将页面,JS,CSS等文本文件或者其他文件通过高压缩算法将其压缩,然后传输到客户端,由客户端的浏览器负责解压缩与呈现。通常能节省40%以上的流量(一般都有60%左右),一些PHP,JSP文件也能够进行压缩。
1.Tomcat 直接开启Gzip
打开Tomcat 目录下的conf下的server.xml,并找到如下信息:
Xml代码 复制代码 收藏代码tomcat <wbr>gzip <wbr>网页压缩技术
  1. <!-- Note : To use gzip compression you could set the following properties :
  2. compression="on"
  3. compressionMinSize="2048"
  4. noCompressionUserAgents="gozilla, traviata"
  5. compressableMimeType="text/html,text/xml"
  6. -->
<!-- Note : To use gzip compression you could set the following properties : compression="on" compressionMinSize="2048" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml" -->

把它们加入到你配置的<Connector port="80" .../>中去。如果要压缩css 和 js,加入compressableMimeType="text/html,text/xml,text/css,text/javascript"。还要压缩图片,加入compressableMimeType="text/html,text/xml,text/css,text/javascript,image/gif,image/jpg"。
开启后重启Tomcat ,通过浏览器查看headers信息就能看到是否开启。

2.使用filter,在代码级别完成web应用的gzip压缩的开启。

(1).CachedResponseWrapper类
实现定制输出的关键是对HttpServletResponse 进行包装,截获所有的输出,等到过滤器链处理完毕后,再对截获的输出进行处理,并写入到真正的HttpServletResponse 对象中。JavaEE 框架已经定义了一个HttpServletResponseWrapp er 类使得包装HttpServletResponse 更加容易。我们扩展这个HttpServletResponseWrapp er,截获所有的输出,并保存到ByteArrayOutputStream 中。
定制的包装响应能方便地从帮助类 HttpServletResponseWrapp er 中导出。这一类粗略地执行许多方法,允许我们简单地覆盖 getOutputStream() 方法以及 getWriter() 方法,提供了定制输出流的实例。
HttpServletResponseWrapp er这个类的使用包括以下五个步骤:
1)建立一个响应包装器。扩展javax.servlet.http.HttpServletResponseWrapp er。
2)提供一个缓存输出的PrintWriter。重载getWriter方法,返回一个保存发送给它的所有东西的PrintWriter,并把结果存进一个可以稍后访问的字段中。
3)传递该包装器给doFilter。此调用是合法的,因为HttpServletResponseWrapp er实现HttpServletResponse。
4)提取和修改输出。在调用FilterChain的doFilter方法后,原资源的输出只要利用步骤2中提供的机制就可以得到。只要对你的应用适合,就可以修改或替换它。
5)发送修改过的输出到客户机。因为原资源不再发送输出到客户机(这些输出已经存放到你的响应包装器中了),所以必须发送这些输出。这样,你的过滤器需要从原响应对象中获得PrintWriter或OutputStream,并传递修改过的输出到该流中。
Java代码 复制代码 收藏代码tomcat <wbr>gzip <wbr>网页压缩技术
  1. class CachedResponseWrapper extends HttpServletResponseWrapper {
  2. public static final int OUTPUT_NONE = 0;
  3. public static final int OUTPUT_WRITER = 1;
  4. public static final int OUTPUT_STREAM = 2;
  5. private int outputType = OUTPUT_NONE;
  6. private int status = SC_OK;
  7. private ServletOutputStream output = null;
  8. private PrintWriter writer = null;
  9. private ByteArrayOutputStream buffer = null;
  10. public CachedResponseWrapper(HttpServletResponse resp) throws IOException {
  11. super(resp);
  12. buffer = new ByteArrayOutputStream();
  13. }
  14. public int getStatus() {
  15. return status;
  16. }
  17. public void setStatus(int status) {
  18. super.setStatus(status);
  19. this.status = status;
  20. }
  21. public void setStatus(int status, String string) {
  22. super.setStatus(status, string);
  23. this.status = status;
  24. }
  25. public void sendError(int status, String string) throws IOException {
  26. super.sendError(status, string);
  27. this.status = status;
  28. }
  29. public void sendError(int status) throws IOException {
  30. super.sendError(status);
  31. this.status = status;
  32. }
  33. public void sendRedirect(String location) throws IOException {
  34. super.sendRedirect(location);
  35. this.status = SC_MOVED_TEMPORARILY;
  36. }
  37. public PrintWriter getWriter() throws IOException {
  38. if (outputType == OUTPUT_STREAM)
  39. throw new IllegalStateException();
  40. else if (outputType == OUTPUT_WRITER)
  41. return writer;
  42. else {
  43. outputType = OUTPUT_WRITER;
  44. writer = new PrintWriter(new OutputStreamWriter(buffer,
  45. getCharacterEncoding()));
  46. return writer;
  47. }
  48. }
  49. public ServletOutputStream getOutputStream() throws IOException {
  50. if (outputType == OUTPUT_WRITER)
  51. throw new IllegalStateException();
  52. else if (outputType == OUTPUT_STREAM)
  53. return output;
  54. else {
  55. outputType = OUTPUT_STREAM;
  56. output = new WrappedOutputStream(buffer);
  57. return output;
  58. }
  59. }
  60. public void flushBuffer() throws IOException {
  61. if (outputType == OUTPUT_WRITER)
  62. writer.flush();
  63. if (outputType == OUTPUT_STREAM)
  64. output.flush();
  65. }
  66. public void reset() {
  67. outputType = OUTPUT_NONE;
  68. buffer.reset();
  69. }
  70. public byte[] getResponseData() throws IOException {
  71. flushBuffer();
  72. return buffer.toByteArray();
  73. }
  74. class WrappedOutputStream extends ServletOutputStream {
  75. private ByteArrayOutputStream buffer;
  76. public WrappedOutputStream(ByteArrayOutputStream buffer) {
  77. this.buffer = buffer;
  78. }
  79. public void write(int b) throws IOException {
  80. buffer.write(b);
  81. }
  82. public byte[] toByteArray() {
  83. return buffer.toByteArray();
  84. }
  85. }
  86. }
 class CachedResponseWrapper extends HttpServletResponseWrapper { public static final int OUTPUT_NONE = 0; public static final int OUTPUT_WRITER = 1; public static final int OUTPUT_STREAM = 2; private int outputType = OUTPUT_NONE; private int status = SC_OK; private ServletOutputStream output = null; private PrintWriter writer = null; private ByteArrayOutputStream buffer = null; public CachedResponseWrapper(HttpServletResponse resp) throws IOException { super(resp); buffer = new ByteArrayOutputStream(); } public int getStatus() { return status; } public void setStatus(int status) { super.setStatus(status); this.status = status; } public void setStatus(int status, String string) { super.setStatus(status, string); this.status = status; } public void sendError(int status, String string) throws IOException { super.sendError(status, string); this.status = status; } public void sendError(int status) throws IOException { super.sendError(status); this.status = status; } public void sendRedirect(String location) throws IOException { super.sendRedirect(location); this.status = SC_MOVED_TEMPORARILY; } public PrintWriter getWriter() throws IOException { if (outputType == OUTPUT_STREAM) throw new IllegalStateException(); else if (outputType == OUTPUT_WRITER) return writer; else { outputType = OUTPUT_WRITER; writer = new PrintWriter(new OutputStreamWriter(buffer, getCharacterEncoding())); return writer; } } public ServletOutputStream getOutputStream() throws IOException { if (outputType == OUTPUT_WRITER) throw new IllegalStateException(); else if (outputType == OUTPUT_STREAM) return output; else { outputType = OUTPUT_STREAM; output = new WrappedOutputStream(buffer); return output; } } public void flushBuffer() throws IOException { if (outputType == OUTPUT_WRITER) writer.flush(); if (outputType == OUTPUT_STREAM) output.flush(); } public void reset() { outputType = OUTPUT_NONE; buffer.reset(); } public byte[] getResponseData() throws IOException { flushBuffer(); return buffer.toByteArray(); } class WrappedOutputStream extends ServletOutputStream { private ByteArrayOutputStream buffer; public WrappedOutputStream(ByteArrayOutputStream buffer) { this.buffer = buffer; } public void write(int b) throws IOException { buffer.write(b); } public byte[] toByteArray() { return buffer.toByteArray(); } } }

(2).GZipFilter类
Java代码 复制代码 收藏代码tomcat <wbr>gzip <wbr>网页压缩技术
  1. public class GZipFilter implements Filter {
  2. public void init(FilterConfig arg0) throws ServletException {
  3. }
  4. public void doFilter(ServletRequest request, ServletResponse response,
  5. FilterChain chain) throws IOException, ServletException {
  6. HttpServletResponse httpResponse = (HttpServletResponse) response;
  7. CachedResponseWrapper wrapper = new CachedResponseWrapper(httpResponse);
  8. // 写入wrapper:
  9. chain.doFilter(request, wrapper);
  10. // 对响应进行处理,这里是进行GZip压缩:
  11. byte[] data = GZipUtil.gzip(wrapper.getResponseData());
  12. httpResponse.setHeader("Content-Encoding", "gzip");
  13. httpResponse.setContentLength(data.length);
  14. ServletOutputStream output = response.getOutputStream();
  15. output.write(data);
  16. output.flush();
  17. }
  18. public void destroy() {
  19. }
  20. }
public class GZipFilter implements Filter { public void init(FilterConfig arg0) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; CachedResponseWrapper wrapper = new CachedResponseWrapper(httpResponse); // 写入wrapper: chain.doFilter(request, wrapper); // 对响应进行处理,这里是进行GZip压缩: byte[] data = GZipUtil.gzip(wrapper.getResponseData()); httpResponse.setHeader("Content-Encoding", "gzip"); httpResponse.setContentLength(data.length); ServletOutputStream output = response.getOutputStream(); output.write(data); output.flush(); } public void destroy() { } }

(3).GZipUtil类
Java代码 复制代码 收藏代码tomcat <wbr>gzip <wbr>网页压缩技术
  1. public final class GZipUtil {
  2. public static byte[] gzip(byte[] data) {
  3. ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240);
  4. GZIPOutputStream output = null;
  5. try {
  6. output = new GZIPOutputStream(byteOutput);
  7. output.write(data);
  8. } catch (IOException e) {
  9. throw new RuntimeException("G-Zip failed.", e);
  10. } finally {
  11. if (output != null) {
  12. try {
  13. output.close();
  14. } catch (IOException e) {
  15. }
  16. }
  17. }
  18. return byteOutput.toByteArray();
  19. }
  20. }
public final class GZipUtil { public static byte[] gzip(byte[] data) { ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(10240); GZIPOutputStream output = null; try { output = new GZIPOutputStream(byteOutput); output.write(data); } catch (IOException e) { throw new RuntimeException("G-Zip failed.", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { } } } return byteOutput.toByteArray(); } }

(4).在web.xml中配置 GZipFilter
Xml代码 复制代码 收藏代码tomcat <wbr>gzip <wbr>网页压缩技术
  1. <filter>
  2. <filter-name>GZipFilter</filter-name>
  3. <filter-class>com.logcd.filter.GZipFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>GZipFilter</filter-name>
  7. <url-pattern>*.html</url-pattern>
  8. </filter-mapping>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值