Data Compression 1 (51), data compression 151

Source: Internet
Author: User

Data Compression 1 (51), data compression 151

1. compress the specified data in a servlet:

PackageCn. hongxing. servlet;

ImportJava. io. ByteArrayOutputStream;

ImportJava. io. IOException;

ImportJava. io. OutputStream;

ImportJava. io. PrintWriter;

ImportJava. io. StringReader;

ImportJava.util.zip. GZIPOutputStream;

ImportJavax. servlet. ServletException;

ImportJavax. servlet. http. HttpServlet;

ImportJavax. servlet. http. HttpServletRequest;

ImportJavax. servlet. http. HttpServletResponse;

Public ClassGzipServletExtendsHttpServlet {

Public VoidDoGet (HttpServletRequest request, HttpServletResponse resp)

ThrowsServletException, IOException {

// Declare the data to be compressed

String str = "Hello, in the memory, declare Hello, Hello, in" +

"In-memory declare a Hello in-memory declare a Hello you" +

"Fortunately, in the memory, declare a <br/> container declaration to be compressed, get to be compressed" +

"The data container Declaration of the byte code of the data to be compressed to obtain the number of bytes to be compressed" +

"The data container of the Data bytecode declares that the data is to be compressed to obtain the data to be compressed" +

"The data containers of bytecode declare that the data is to be compressed to obtain the bytecode of the data to be compressed" +

"Declare a container declaration in the memory that the data is to be compressed to obtain the data to be compressed" +

"Bytecode data ";

// 2: Get the bytecode of the data to be compressed

Byte[] Src = str. getBytes ("UTF-8 ");

// 3: declare a container in the memory

ByteArrayOutputStream destByte =NewByteArrayOutputStream ();

// 4: declare the compressed tool stream and set the compression destination to destByte

GZIPOutputStream zip =NewGZIPOutputStream (destByte );

// 5: Write Data

Zip. write (src );

// 6: Close the compression tool stream

Zip. close ();

System.Err. Println ("size of bytecode before compression:" + src. length );

// 7: Obtain compressed data

Byte[] Dest = destByte. toByteArray ();

System.Err. Println ("Size of the compressed bytecode:" + dest. length );

// 8: The Bytes array after compression must be output.

Resp. setContentType ("text/html; charset = UTF-8 ");

// 9: The byte stream must be used to output information.

OutputStream out = resp. getOutputStream ();

// 10: Notify the browser. This is compressed data and requires the browser to decompress it.

Resp. setHeader ("Content-encoding", "gzip ");

// 11: the length of the compressed data of the notification Browser

Resp. setContentLength (dest. length );

// 10: Output

Out. write (dest );

}

}

2: All pages *. All jsp Compression

There are only two ways to output information:

Respoonse. getWriter ()..[W1]Output Information-response stream. AllJspPage. After compilationJspWriterMethod.

But allJspAll pagesJspWriter, AndJspwriterYesPrintWriter.

Response. getOutputStream ()--Byte stream.

Analysis: If you want to implement full-site compression, first implementServletInResp. getWriterThe output data is compressed.

First, compress one file.

Step 1: Write a Servlet class. Normal output information

: Resp., getWriter (). print (.....);

Public ClassOneServletExtendsHttpServlet {

Public VoidDoGet (HttpServletRequest request, HttpServletResponse response)

ThrowsServletException, IOException {

Response. setContentType ("text/html; charset = UTF-8 ");

PrintWriter out = response. getWriter ();

Out. println ("Hello everyone ");

}

}

Step 2: intercept the above class and encapsulate response in the interception process.

Implementation image class: HttpServletResponseWrapper-
PackageCn. hongxin. filter;

ImportJava. io. IOException;

ImportJavax. servlet. Filter;

ImportJavax. servlet. FilterChain;

ImportJavax. servlet. FilterConfig;

ImportJavax. servlet. ServletException;

ImportJavax. servlet. ServletRequest;

ImportJavax. servlet. ServletResponse;

ImportJavax. servlet. http. HttpServletResponse;

ImportJavax. servlet. http. HttpServletResponseWrapper;

Public ClassGzipFilterImplementsFilter {

Public VoidInit (FilterConfig filterConfig)ThrowsServletException {

}

Public VoidDoFilter (ServletRequest request, ServletResponseresponse,

FilterChain chain)ThrowsIOException, ServletException {

// Declare the MyResponse packaging class

MyResponseresp =NewMyResponse (HttpServletResponse) response );

// When running the program, the encapsulated class must be passed.

Chain. doFilter (request, resp );

}

Public VoidDestroy (){

}

}

// Package HttpSerlvetResponse

ClassMyResponseExtendsHttpServletResponseWrapper {

PublicMyResponse (HttpServletResponse response ){

Super(Response );

}

}

Step 3: to compress data, we must intercept the getwriter method.

Not returnedApacheOfWrtiterObject.

The complete code is as follows:

PackageCn. hongxing. filter;

Public ClassGzipFilterImplementsFilter {

Public VoidInit (FilterConfig filterConfig)ThrowsServletException {

}

Public VoidDoFilter (ServletRequest request, ServletResponseresponse,

FilterChain chain)ThrowsIOException, ServletException {

// Declare the MyResponse packaging class

MyResponseresp =NewMyResponse (HttpServletResponse) response );

// When running the program, the encapsulated class must be passed.

Chain. doFilter (request, resp );

// If the target class is called successfully, the returned result is reading a.txt.

Filefile =NewFile ("d:/a/a.txt ");

// Declare a cached String object

StringBuildersb =NewStringBuilder ();

// Read the file

InputStreamin =NewFileInputStream (file );

Byte[] B =New Byte[1024];

IntLen = 0;

While(Len = in. read (B ))! =-1 ){

Sb. append (NewString (B, 0, len, "UTF-8 "));

}

In. close ();

// Compress into bytes

Byte[] Src = sb. toString (). getBytes ("UTF-8 ");

// Declare the cache container

ByteArrayOutputStreamdestBytes =NewByteArrayOutputStream ();

// Declare the compressed stream

GZIPOutputStreamgzip =NewGZIPOutputStream (destBytes );

// Compress data

Gzip. write (src );

Gzip. close ();

// Obtain compressed data

Byte[] Dest = destBytes. toByteArray ();

System.Err. Println ("before compression:" + src. length );

System.Err. Println ("after compression:" + dest. length );

// Output

// Native response must be used

HttpServletResponseres = (HttpServletResponse) response;

Res. setContentType ("text/html; charset = UTf-8 ");

OutputStreamout = res. getOutputStream ();

Res. setHeader ("Content-encoding", "gzip"); // required

Res. setContentLength (dest. length );

Out. write (dest );

}

Public VoidDestroy (){

}

}

// Package HttpSerlvetResponse

ClassMyResponseExtendsHttpServletResponseWrapper {[W8]

PublicMyResponse (HttpServletResponse response ){

Super(Response );

}

@ Override

PublicPrintWriter getWriter ([W9])ThrowsIOException {

System.Err. Println ("someone wants to get the output stream ");

PrintWriter out =NewPrintWriter [W10] (

NewOutputStreamWriter (

NewFileOutputStream ("d:/a/a.txt"), "UTF-8 "));

ReturnOut;

}

}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.