0

Inside spring controller writes an excel stream into response

     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. 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. 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.

Any pointers what is wrong.Is there alternate way to do achive this.

Spring 3.1, JDK 1.7

Aarati
  • 321
  • 1
  • 10

1 Answers1

0

Oups, a spring-mvc interceptor is not a filter. 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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Thanks for info. Initially had implemented simple filter & configured it in web.xml, however it was not called after controller method exit. May be spring internal filter hierarchy is not calling this filter or ordering is wrong in filter chain. Any pointers in this direction would be appreciated – Aarati Aug 17 '17 at 06:51
  • 1
    Plain filters are directly called by the servlet container and are normally independant of spring-mvc. But it should be called *around* spring-mvc DispatcherServlet: `void doFilter(...) { /* before servlet */ chain.doFilter(...); /* after servlet */ }`. Read again the answer in the linked post... – Serge Ballesta Aug 17 '17 at 07:23
  • Finally TeeOutputStream worked to fetch servletoutputstream. Thanks to this post https://stackoverflow.com/questions/10457963/spring-rest-service-retrieving-json-from-request – Aarati Aug 18 '17 at 09:38