Rudziankoŭ
Rudziankoŭ

Reputation: 11251

Replace response body using filter

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.

Upvotes: 1

Views: 3977

Answers (1)

Rudziankoŭ
Rudziankoŭ

Reputation: 11251

You should pass wrapper to doFilter method:

chain.doFilter(request,capturingResponseWrapper);

Upvotes: 1

Related Questions