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?