来源:京东云开发者
一、问题回溯
{"code":-1,"msg":"失败"}/** * 模板下载 */@RequestMapping("/doBatchWareSetAd")public void doBatchWareSetAd(@RequestParam MultipartFile file, HttpServletResponse response) { wareBatchBusiness.doBatchWareSetAd(file, response, getLongOrgCode(), getCurrentUserPin(), getCurrentUserId());}/** * 模板下载 */@RequestMapping("/doBatchWareSetAdDemo")@ResponseBodypublic Map<String, Object> doBatchWareSetAd(@RequestParam MultipartFile file, HttpServletResponse response) { return wareBatchBusiness.doBatchWareSetAd(file, response, getLongOrgCode(), getCurrentUserPin(), getCurrentUserId());}
("/test1")public Map<String, String> test1(HttpServletResponse response) {Map<String, String> map = new HashMap<>();map.put("1", "1");return map;}// 响应JSON报文

("/test2")public Map<String, String> test2(HttpServletResponse response) throws IOException {Map<String, String> map = new HashMap<>();map.put("1", "1");response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", String.format("attachment; filename=%s_%s.xls", "Demo", System.currentTimeMillis()));OutputStream out = response.getOutputStream();out.flush();out.close();return map;}// 响应提示下载文件


启发:
聊了这么多,那我们这种类似场景的代码应该怎么写?
既然主动写入流会解除@ResponseBody的作用,反之又能发挥它的作用,那我们最佳方案是不是如下所示?
("/test1")public Map<String, String> test1(HttpServletResponse response) {Map<String, String> map = new HashMap();if (获取不到文件配置 == true) {return map.put("msg", "获取不到文件配置");}response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", String.format("attachment; filename=%s_%s.xls", "Demo", System.currentTimeMillis()));OutputStream out = response.getOutputStream();out.flush();out.close();return map;}
如此一来,当发生预期之外的情况,我们有非常明显的报错提示,当正常时又可以完美实现功能,妙哉(我觉得)~
-end-
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70027824/viewspace-3000237/ ,如需转载,请注明出处,否则将追究法律责任。