1

I have tried the following example to replace some content in my servlet response.

Programming Customized Requests and Responses

test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <link th:href="@{/css/test.css}" rel="stylesheet"></link>
    <title>Test</title>
</head>
<body>
    <p class="forbiddenClass">Test!</p>
</body>
</html>

test.css:

.forbiddenClass {
    color: red;
}

CharResponseWrapper.java

public class CharResponseWrapper extends HttpServletResponseWrapper {

    private final CharArrayWriter output;

    public CharResponseWrapper(final HttpServletResponse response) {
        super(response);
        output = new CharArrayWriter();
    }

    public String toString() {
        return output.toString();
    }

    public PrintWriter getWriter() {
        return new PrintWriter(output);
    }
}

ClassReplacementFilter.java

@Component
public class ClassReplacementFilter extends GenericFilterBean {

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
            throws IOException, ServletException {

        final CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
        chain.doFilter(request, wrapper);

        String content = wrapper.toString();
        if (StringUtils.isEmpty(content)) {
            System.out.println("content is empty for content type: " + response.getContentType());
        } else {
            content = content.replaceAll("forbiddenClass", "correctClass");
            response.setContentLength(content.getBytes().length);
            response.getOutputStream().write(content.getBytes());
        }
    }
}

As you might see, I want to replace the string forbiddenClass with correctClass, but it only works for the html file. The content of test.css does not change and the following message of the filter is printed to output.

content is empty for content type: text/css;charset=UTF-8

Why is the content empty for test.css?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Max Peterson
  • 129
  • 1
  • 1
  • 4

1 Answers1

1

Why is the content empty for test.css?

Because you only captured whatever is written to response.getWriter(), not whatever is written to response.getOutputStream().

You need the HttpServletResponseWrapper implementation as shown in bottom of this answer to a related question: Catch-all servlet filter that should capture ALL HTML input content for manipulation, works only intermittently.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555