2015-12-23 107 views
1

我試圖重現this example使用過濾器

更換反應的身體我已代碼:

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錯誤:

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); 我不收回任何例外,但我得到空白的答覆正文。

+1

傳遞給doFilter的原始響應()方法,你應該通過不寫什麼到OutputStream的使用ResponseWrapper。如果原始響應通過,控制返回到過濾器就太遲了。 http://stackoverflow.com/a/14736818/185565 – Whome

回答

0

你應該通過包裝來doFilter方法:

chain.doFilter(request,capturingResponseWrapper);