java---GZIP压缩技术演示(结合XML文档配置,网页显示)

来源:互联网 发布:ubuntu 添加启动脚本 编辑:程序博客网 时间:2024/06/10 16:46
<pre name="code" class="html">XML文档配置
<servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>GzipServlet</servlet-name>    <servlet-class>cn.hncu.img.GzipServlet</servlet-class>  </servlet><servlet-mapping>    <servlet-name>GzipServlet</servlet-name>    <url-pattern>/gzip</url-pattern> </servlet-mapping>
</pre><pre code_snippet_id="1769887" snippet_file_name="blog_20160718_1_4654779" name="code" class="java">配合网页<pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <script type="text/javascript">       <script type="text/javascript">    </script>  </head>    <body>         <a href ="gzip">演示gzip</a>               </body>  </html>
package cn.hncu.img;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.zip.GZIPOutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GzipServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request,response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String str="sdjkjewjw信息科学与工程学院kekw";byte[] src = str.getBytes();System.out.println("src-length:"+src.length);//把字节数组src中的数据 压缩到  array内存流当中ByteArrayOutputStream array = new ByteArrayOutputStream();GZIPOutputStream gOut = new GZIPOutputStream(array);gOut.write(src);gOut.close();//从内存流array中把压缩后的数据拿出来byte[] dest = array.toByteArray();System.out.println("dest-length:"+dest.length);response.setContentType("text/html");response.setHeader("Content-Encoding","gzip");//告诉浏览器,当前发送的是gzip格式的内容//response.setContentLength(dest.length);//设内容长度---法1response.setHeader("Content-Length", ""+dest.length);//设内容长度---法2OutputStream out = response.getOutputStream();//out.write(src);out.write(dest);out.flush();out.close();}}




0 0