1

I am trying to reproduce this example

I have code:

public void  doFilter(ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
            throws java.io.IOException, ServletException {
    HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper(
            (HttpServletResponse) response);
    // Pass request back down the filter chain

    chain.doFilter(request,response);
    if (response.getContentType() != null
            && response.getContentType().contains("text/html")) {

        String content = capturingResponseWrapper.getCaptureAsString();

        // replace stuff here
        String replacedContent = content.replaceAll(
                "<h2[^>]*>(.*?)</h2>",
                "<h3>$1 - HTML replaced</h3>");

        System.out.println(replacedContent);

        response.getWriter().write(replacedContent);

    }

Executing this code by navigating to html page I receive 500 error:

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Did I misuse something? If I get rid of chain.doFilter(request,response); I don't recive any exceptions, but I get blank response body.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • 1
    You pass the original response to doFilter() method, you should pass a responsewrapper which does not write anything to a outputstream. It is too late once control is returned back to a filter if the original response was passed. http://stackoverflow.com/a/14736818/185565 – Whome Dec 23 '15 at 21:54

1 Answers1

1

You should pass wrapper to doFilter method:

chain.doFilter(request,capturingResponseWrapper);
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192