1. 程式人生 > >java---GZIP壓縮技術演示(結合XML文件配置,網頁顯示)

java---GZIP壓縮技術演示(結合XML文件配置,網頁顯示)

<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);//設內容長度---法1
		response.setHeader("Content-Length", ""+dest.length);//設內容長度---法2
		
		OutputStream out = response.getOutputStream();
		//out.write(src);
		out.write(dest);
		out.flush();
		out.close();

	}

}