Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This is about changing a servlet's output,...
Fitting it into some weird company layout. Handy if the company name changes yet again...
This is done by using a filter class.
We don't pass the original response to the servlet,...
but a response impersonator,...
is passed when we have the servlet activated,...
so the servlet will get the filter class's writer instead of the usual one ...
and will write to a StringWriter, that actually contains a StringBuffer.
That means we can read and add to or edit the String /document /page afterwards,...
while sending it to the REAL response.
Instead of postprocessing we can also do a bit of preprocessing by passing a parameter to the servlet as an attribute. In general, we can change or add to the headers that are part of the request.
The assumption with the technique shown is, that the servlet actually writes lines of text, using println. This applies to most text-outputting servlets, but in less simple cases, the HTML or XML servlet-output will have to be parsed.
The filter class implements the javax.servlet.Filter interface, so it contains 3 methods.
This gets the first shot, as defined in the web.xml.
Multiple filters can be chained, hence this parameter, chain.
In this lesson, next in the chain is just our servlet,...
or could be this jsp.
The extension sx is what triggers the filter.
The technique shown can be used to convert plain text output to HTML, XML, etc.
With a servlet serving plain text, its output could be converted to HTML by writing HTML and BODY tags to the response first, BR tags instead of endofline-characters , plus closing tags. A splendid combination with this would be CSS.
A servlet can write either strings or bytes, that's why these 2 methods are here.
In this example only strings are written.
getOutputStream could be used where a servlet serves a PNG image and the filter sets a different transparent color than the servlet does, so it gives a chance to change a binary stream as opposed to text.
Initial sizes, they can grow, but this is costly.
Choose the inital size wisely, in that most servlet output will fit in the size given.
If the expected sizes are in MB's, the technique shown had better not be used. In that case the stream written by the servlet will have to be read and handled by the filter WHILE it is being written. Another solution would be to store the servlet's output in a temporary file or in a database, so you can deal with it afterward.
To keep this example simple, the assumption was, that no servlet will try to call getOutputStream instead of getWriter.
Another assumption is, that the <BODY> tag is just on a single line and there's nothing else on that line.
Similar for the closing tag.
Instead of this...
we can also mention a path,...
or even a servlet-name.
If parsing is necessary, you can use classes like
for XML parsing.
This parameter ...
can be retrieved ...