Time to code. We end this chapter by looking at the code for both the compression filter and the wrapper it uses. We’re expanding from the previous discussion, and while there is some new stuff here, it’s mostly just plain Java code.
This filter provides a mechanism to compress the response body content. This type of filter would commonly be applied to any text content such as HTML, but not to most media formats such as PNG or MPEG, because they are already compressed.
You don’t need to study this code for the exam.
The rest of this example is a demonstration of a response filter in action, just so that you can see something a little more real-world. You don’t need to learn or understand this particular example for the exam, so consider the rest of this chapter completely optional.
To test this filter, comment out this line of code. You should see illegible, compressed data in your browser.
Compression meets HTTP
How does the server know it can send compressed data? How does the browser know when it’s getting compressed data? It turns out that HTTP is “compression-aware”; here’s how it works:
One of the headers that the browser sends (“Accept-Encoding: gzip”), tells the server about the browser’s capabilities for dealing with different types of content.
If the server sees that the browser can deal with compressed data, it will perform the compression, and add a header (“Content-Encoding: gzip”), to the response.
When the browser receives the response, the “Content-Encoding: gzip” header tells the browser to de-compress the data before it is displayed.