GZip compression of the response is enabled by wrapping the HttpServletResponse object in a GZipServletResponseWrapper
. This wrapper is passed to the Servlet, JSP etc. which handles the request. When the Servlet, JSP etc. writes output to be sent to the browser, it does so to the response wrapper object. The Servlet, JSP etc. cannot see the difference between a real HttpServletResponse and the wrapper object. The response wrapper object then compresses the written content and writes the compressed content to the HttpServletResponse. Quite simple
Here is the GZip Servlet filter code. There are not really that many ways you can write it. It is pretty straightforward.please advise
The code consists of 3 classes. A GZipServletFilter, a GZipServletResponseWrapper
and a GZipServletOutputStream.
The GZipServletOutputStream is what compresses the content written to it. It does so by using a GZIPOutputStream internally, which is a standard Java class.
When the GZipServletResponseWrapper
gives back an OutputStream or PrintWriter to a Servlet or JSP, it is either a GZipServletOutputStream or a PrintWriter that writes to the GZipServletOutputStream which is returned.
The GZipServletFilter is what intercepts the requests, checks if the client accepts compression or not, and enables compression if it does. It does so by wrapping the HttpServletResponse in a GZipServletResponseWrapper
before passing it down the filter chain.
From novice to tech pro — start learning today.