我試過以下示例來替換我的servlet響應中的某些內容。CharResponseWrapper捕獲的內容爲空
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());
}
}
}
正如你可能會看到,我想correctClass
替換字符串forbiddenClass
,但它僅適用於HTML文件。 test.css的內容不會更改,並且會輸出以下過濾器消息。
content is empty for content type: text/css;charset=UTF-8
爲什麼test.css中的內容爲空?
非常感謝,這就是解決方案。 –