本文介绍了使用过滤器更换响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试复制此示例
我有代码:
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);
}
通过导航到html页面执行此代码,我收到500错误:
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)
我滥用吗?如果我摆脱了 chain.doFilter(request,response);
我没有接受任何例外,但响应正文为空.
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.
推荐答案
您应该将包装器传递给 doFilter
方法:
You should pass wrapper to doFilter
method:
chain.doFilter(request,capturingResponseWrapper);
这篇关于使用过滤器更换响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!