Servlet uses gzip to send web compressed documents

Source: Internet
Author: User

Gzip is short for gnuzip. It is a File compression program of GNU free software. Gzip was first created by Jean-Loup gailly and Mark Adler for File compression in UNIX systems. We often use files suffixed with .gz in linux, which are in GZIP format. Nowadays, it has become a widely used data compression format on the Internet, or a file format. The gzip text compression solution can greatly reduce the size of HTML pages or plain text. Most browsers know how to deal with gzip compressed content. browsers that support this function will set the accept-encoding request header;

Here is a simple demo implementation:

Package servletreview; import Java. io. ioexception; import Java. io. printwriter; import java.util.zip. gzipoutputstream; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; public class gziputils {// determine whether the browser supports the gzip decompression function public static Boolean isgzipsupported (httpservletrequest request) {string encodings = request based on the header. getheader ("Accept-encoding"); Return (encodings! = NULL) & (encodings. indexof ("gzip ")! =-1);} // determines whether the public static Boolean isgzipdisabled (httpservletrequest request) {string flag = request is enabled for the gzip function. getparameter ("disablegzip"); Return (flag! = NULL )&&(! Flag. equalsignorecase ("false");} // returns the printwriter public static printwriter getgzipwriter (httpservletresponse response) after gzip compression {try {return (New printwriter (New gzipoutputstream (response. getoutputstream ();} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace (); return NULL ;}}}
Package servletreview; import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; public class longservlet extends httpservlet {/*** servlet use gzip compression */Private Static final long serialversionuid = 7807987641014318123l; Public void doget (H Ttpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html"); printwriter out; If (gziputils. isgzipsupported (request )&&! Gziputils. isgzipdisabled (request) {out = gziputils. getgzipwriter (response); response. setheader ("content-encoding", "gzip");} else {out = response. getwriter () ;} stringbuffer = new stringbuffer (); stringbuffer. append ("<Table>"); For (INT I = 0; I <1000; I ++) {stringbuffer. append ("<tr> <TD>" + I + "</TD> </tr>");} stringbuffer. append ("</table>"); out. println (stringbuffer. tostring (); out. close ();}}
<body><% String path = request.getContextPath(); %> <form action="<%=path %>/longServlet" method="get"> <input type="submit" value="submit"> </form> </body>
 <servlet>         <servlet-name>LongServlet</servlet-name>         <servlet-class>ServletReview.LongServlet</servlet-class>     </servlet>     <servlet-mapping>         <servlet-name>LongServlet</servlet-name>         <url-pattern>/longServlet</url-pattern>     </servlet-mapping> 

Output by accessing the JSP page:

0

1

2

3

...

 

The servlet HTTP request header list, HTTP request header, and their meanings are attached:
Accept: the MIME type acceptable to the browser. Servlet checks accept to determine which format is returned to client resources. IE6 and 7 bugs: re-loading the accept header sent by the page is incorrect, but it is correct in the initial request.

Accept-charset: the acceptable character set of the browser.

Accept-encoding: The data encoding method that the browser can decode, such as gzip. Servlet can return gzip-encoded HTML pages to a browser that supports gzip. In many cases, this can reduce the download time by 5 to 10 times. Before using any type of content encoding, check the accept-dncoding header.

Accept-language: the type of language that the browser wants to use when the server can provide more than one language version.

Authorization: authorization information, usually displayed in the response to the www-Authenticate header sent by the server.

Connection: Indicates whether a persistent connection is required. If the servlet sees that the value here is "keep-alive", or the request uses HTTP 1.1 (HTTP 1.1 performs a persistent connection by default), it can take advantage of the advantages of persistent connections, when a page contains multiple elements (such as an applet or image), the download time is significantly reduced. To achieve this, the servlet needs to send a Content-Length header in the response. The simplest method is to write the content into bytearrayoutputstream first, then, calculate the size of the content before writing it.

Content-Length: the length of the Request Message Body.

COOKIE: This is one of the most important request header information.

From: the e-mail address of the Request sender, which is used by some special Web client programs and not used by the browser.

HOST: host and port in the initial URL.

If-modified-since: it is returned only when the requested content is modified after the specified date. Otherwise, the 304 "not modified" response is returned.

Pragma: specifying the "no-Cache" value indicates that the server must return a refreshed document, even if it is a proxy server and has a local copy of the page.

Referer: contains a URL from which you can access the current requested page.

User-Agent: browser type. This value is useful if the content returned by the servlet is related to the browser type. Use the User-Agent only when not required. Check whether it is null when using it. To distinguish between Netscape and IE, check MSIE instead of "Mozilla ". This header can be added and Servlet cannot distinguish this situation.

UA-pixels, UA-color, UA-OS, UA-CPU: non-standard request headers sent by some versions of IE browser, indicating screen size, color depth, and cputype.

out.println("Protocol: " + request.getProtocol()); out.println("Scheme: " + request.getScheme()); out.println("Server Name: " + request.getServerName() ); out.println("Server Port: " + request.getServerPort()); out.println("Protocol: " + request.getProtocol()); out.println("Server Info: " + getServletConfig().getServletContext().getServerInfo()); out.println("Remote Addr: " + request.getRemoteAddr()); out.println("Remote Host: " + request.getRemoteHost()); out.println("Character Encoding: " + request.getCharacterEncoding()); out.println("Content Length: " + request.getContentLength()); out.println("Content Type: "+ request.getContentType()); out.println("Auth Type: " + request.getAuthType()); out.println("HTTP Method: " + request.getMethod()); out.println("Path Info: " + request.getPathInfo()); out.println("Path Trans: " + request.getPathTranslated()); out.println("Query String: " + request.getQueryString()); out.println("Remote User: " + request.getRemoteUser()); out.println("Session Id: " + request.getRequestedSessionId()); out.println("Request URI: " + request.getRequestURI()); out.println("Servlet Path: " + request.getServletPath()); out.println("Accept: " + request.getHeader("Accept")); out.println("Host: " + request.getHeader("Host")); out.println("Referer : " + request.getHeader("Referer")); out.println("Accept-Language : " + request.getHeader("Accept-Language")); out.println("Accept-Encoding : " + request.getHeader("Accept-Encoding")); out.println("User-Agent : " + request.getHeader("User-Agent")); out.println("Connection : " + request.getHeader("Connection")); out.println("Cookie : " + request.getHeader("Cookie")); out.println("Created : " + session.getCreationTime()); out.println("LastAccessed : " + session.getLastAccessedTime());

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.