Rabu, 29 Januari 2014

WhitespaceFilter






Whitespace


Whitespace is used everywhere. It covers spaces, tabs and newlines. It is used to distinguish lexical tokens from each other and also to keep the source code readable for the developer. But in case of HTML over network, whitespace costs bandwidth and therefore in some circumstances also money and/or performance. If you care about the bandwidth usage and/or the money and/or performance, then you can consider to trim off all whitespace of the HTML response. The only con is that it makes the HTML source code at the client side almost unreadable.



You can trim whitespace right in the HTML files (or JSP or JSF or whatever view you're using, as long as it writes plain HTML response), but that would make the source code unreadable for yourself. Better way is to use a Filter which trims the whitespace from the response.


Back to top


Replace response writer


Here is how such a WhitespaceFilter can look like. It is relatively easy, it actually replaces the writer of the HttpServletResponse with a customized implementation of PrintWriter. This implemetation will trim whitespace off from any strings and character arrays before writing it to the response stream. It also take care of any

 and