Cannot call sendError() after the response has been committed
阿新 • • 發佈:2018-12-15
在一個springboot專案中,使用Apache的POI框架匯出Excel表格時,遇到這個問題,百度了下,大概意思是response已經提交,無法傳送錯誤資訊。Excel表格能正常匯出,只是控制檯一直輸出這個錯誤,於是想辦法改正。檢查controller和service層,都沒有發現問題,後來去匯出表格的工具方法中檢查。
public void exportExcel(HttpServletResponse response, List<T> list, String[] header) throws Exception { Date dt = new Date(); String fileName = new Long(dt.getTime()).toString(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls"); // File file =new File("E:\\"+fileName+".xls"); OutputStream out = response.getOutputStream(); // OutputStream out =new FileOutputStream(file); try { exportExcel(header, list, out, "yyyy-MM-dd"); out.flush(); } catch (Exception e) { throw e; } finally { out.close(); } }
發現這幾句程式碼有點問題
OutputStream out = response.getOutputStream();
try {
...
} catch (Exception e) {
throw e;
} finally {
out.close();
}
我在controller的方法上加了@ResponseBody的註解,而且匯出excel方法返回了Json,但是在匯出excel的工具類方法中已經將response生產的OutputStream關閉,但是@ResponseBody註解使用的就是response的OutputStream輸出的方法,所以此處衝突報錯。 解決的方法就是將Controller層匯出的方法返回型別改為void