CharResponseWrapper捕获的内容为空

时间:2016-02-24 15:35:37

标签: spring servlets servlet-filters

我尝试了以下示例来替换servlet响应中的一些内容。

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());
        }
    }
}

正如您可能看到的,我想用forbiddenClass替换字符串correctClass,但它仅适用于html文件。 test.css的内容不会更改,并且会打印过滤器的以下消息。

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

为什么test.css的内容为空?

1 个答案:

答案 0 :(得分:0)

  

为什么test.css的内容为空?

因为您只捕获了写入response.getWriter()的内容,而不是写入response.getOutputStream()的内容。

您需要HttpServletResponseWrapper实施,如相关问题的答案底部所示:Catch-all servlet filter that should capture ALL HTML input content for manipulation, works only intermittently