EncodedPage.java Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output.

EncodedPage.java  Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output. 

package cwp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;

/** Example showing benefits of gzipping pages to browsers
 *  that can handle gzip.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class EncodedPage extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    String encodings = request.getHeader("Accept-Encoding");
    String encodeFlag = request.getParameter("encoding");
    PrintWriter out;
    String title;
    if ((encodings != null) &&
        (encodings.indexOf("gzip") != -1) &&
        !"none".equals(encodeFlag)) {
      title = "Page Encoded with GZip";
      OutputStream out1 = response.getOutputStream();
      out = new PrintWriter(new GZIPOutputStream(out1), false);
      response.setHeader("Content-Encoding", "gzip");
    } else {
      title = "Unencoded Page";
      out = response.getWriter();
    }
    out.println(ServletUtilities.headWithTitle(title) +
                "\n" +
                "
" + title + "
\n");
    String line = "Blah, blah, blah, blah, blah. " +
                  "Yadda, yadda, yadda, yadda.";
    for(int i=0; i<10000; i++) {
      out.println(line);
    }
    out.println("");
    out.close();
  }
}

Permanent link to this article: http://bangla.sitestree.com/encodedpage-java-servlet-that-shows-the-bandwidth-benefits-of-gzipping-pages-to-browsers-that-can-handle-gzip-uses-the-servletutilities-class-to-simplify-the-doctype-and-head-output/

Leave a Reply