*/
public class StringOutputStream
extends ServletOutputStream {
private StringWriter stringWriter;
public StringOutputStream(StringWriter stringWriter) {
this.stringWriter = stringWriter;
}
public void write(int c) {
stringWriter.write(c);
}
}
Chapter 5 ?– Servlet and JSP Filters 238
response modification needs might be in the future, preparing the setup for better
code reuse. The next subsection includes an example of this process.
Listing 5.17 ModificationFilter.java
package coreservlets.filters;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Generic modification filter that buffers the output and lets
* doModification method change the output string before sending
* it to the real output, i.e., the client. This is an abstract
* class: you
must override doModification in a subclass.
*/
public abstract class ModificationFilter implements Filter {
protected FilterConfig config;
private HttpServletRequest request;
private HttpServletResponse response;
public void doFilter(ServletRequest req,
ServletResponse resp,
FilterChain chain)
throws ServletException, IOException {
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
StringWrapper responseWrapper = new StringWrapper(response);
// Invoke resource, accumulating output in the wrapper.
chain.doFilter(request, responseWrapper);
// Turn entire output into one big String.
Pages:
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290