简体   繁体   English

Spring拦截器读取响应OutputStream

[英]Spring interceptor read response OutputStream

Inside spring controller writes an excel stream into response 内部spring控制器将Excel流写入响应

     HSSFWorkbook workbook = getWorkbook();
     OutputStream out = response.getOutputStream();     
     response.setHeader("pragma", "public");
     response.setHeader("Cache-Control", "public");
     response.setContentType("application/vnd.ms-excel");      
     response.setHeader("Content-Disposition", "attachment;filename=sampleexcel.xls");      
     workbook.write(out);        
     out.close();
     // response.flushBuffer();

As per this link How to read and copy the HTTP servlet response output stream content for logging implementated responsewrapper. 按照此链接, 如何读取和复制HTTP Servlet响应输出流内容以记录实现的responsewrapper。 Below is Interceptor code, 以下是拦截器代码,

      public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

       HttpServletResponseCopier resp=  new HttpServletResponseCopier(response) ;         
       byte[] responseData = resp.getCopy();            
        System.out.println("length "+responseData.length); // its 0 bytes

    }

Basically want to read the Outputstream contents into a temp file. 基本上想将Outputstream的内容读入一个临时文件。 Then add encryption information in it. 然后在其中添加加密信息。 Finally write this encrypted file into response stream. 最后将此加密文件写入响应流。 In above code,resp.getCopy() is empty,hence it writes 0 bytes into temp file. 在上面的代码中,resp.getCopy()为空,因此它将0字节写入临时文件。

Any pointers what is wrong.Is there alternate way to do achive this. 任何指针出了什么问题,是否有其他方法可以做到这一点。

Spring 3.1, JDK 1.7 Spring 3.1,JDK 1.7

Oups, a spring-mvc interceptor is not a filter. 糟糕,spring-mvc拦截器不是过滤器。 It provides hooks to be called before controller execution, after controller execution and after view generation, but cannot replace the response. 它提供了在控制器执行之前,控制器执行之后和视图生成之后要调用的钩子,但是不能替换响应。

The filter used in the referenced post actually replace the response with a wrapper so that everything that is written to the response actually goes into the wrapper and is processed at the time it is written. 在引用的帖子中使用的过滤器实际上是用包装器替换响应,以便写入响应的所有内容实际上都进入包装器,并在编写时进行处理。 Here you only create the wrapper once everything has been written so it can only intercept... nothing. 在这里,只有在所有内容都写完之后才创建包装器,因此它只能拦截……什么也没有。

You will have to implement a filter and a custom response wrapper to achieve your goal. 您将必须实现一个过滤器和一个自定义响应包装器以实现您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM