Servlet/Jsp implement Gzip Technology for sending and compressing Web pages
(1) don't talk about anything. It means that the page is compressed and sent! It is said that the length of the page can be increased by several hundred times!
(2) Note: not all browsers support compressing the sending and receiving of pages. Therefore, code should be used for verification. If yes, it cannot be sent.
The message is sent normally;
(That is, check the Accept-Encoding header in the HTTP header and check whether the header contains items related to gzip. If yes, it uses the PrintWriter
Install GZIPOutputStream. If it is not supported, the page will be sent normally, and a function is added to prohibit page compression !)
(3) display the servlet on the page
package com.lc.ch04Gzip;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 {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out;if (GzipUtilities.isGzipSupported(request)&& !GzipUtilities.isGzipDisabled(request)) {out = GzipUtilities.getGzipWriter(response);response.setHeader("Content-Encoding", "gzip");} else {out = response.getWriter();}String docType = "\n";String title = "Long Page";out.println(docType + "\n" + "" + title+ "\n" + "\n"+ "" + title + "\n");String line = "Bfsdfdsfdsflah, blfsdfdsfah, blasfdsdfh, blsdfdsfah, bldfsdfsdfah. "+ "Yaddsfdsdfa, ysfdsdfadda, yadsdfsdfdsda, yasdfsdfdsfdda.";for (int i = 0; i < 10000; i++) {out.println(line);}out.println("");out.close(); // Needed for gzip; optional otherwise.}}
(4) Compressed classes
package com.lc.ch04Gzip;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 GzipUtilities { public static boolean isGzipSupported (HttpServletRequest request) { String encodings = request.getHeader("Accept-Encoding"); return((encodings != null) && (encodings.indexOf("gzip") != -1)); } public static boolean isGzipDisabled (HttpServletRequest request) { String flag = request.getParameter("disableGzip"); return((flag != null) && (!flag.equalsIgnoreCase("false"))); } public static PrintWriter getGzipWriter (HttpServletResponse response) throws IOException { return(new PrintWriter (new GZIPOutputStream (response.getOutputStream()))); }}(5) demonstration effect: (the effect is good, but there is no comparison. However, it should be possible to compress general images without compression !)
OK!