
一、问题回溯
2023年Q2某日运营反馈一个问题,商品系统商家中心某批量工具模板无法下载,导致功能无法使用(因为模板是动态变化的)
{"code":-1,"msg":"失败"}
/*** 模板下载*/("/doBatchWareSetAd")public void doBatchWareSetAd( MultipartFile file, HttpServletResponse response) {wareBatchBusiness.doBatchWareSetAd(file, response, getLongOrgCode(), getCurrentUserPin(), getCurrentUserId());}
/*** 模板下载*/("/doBatchWareSetAdDemo")public Map<String, Object> doBatchWareSetAd( 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;}// 响应提示下载文件
-
我们要相信自己的代码,至少是要相信已经经过测试的代码。 -
在委托他人或者自己配置环境参数,如权限、ZK等每次都保证预发布和线上同时配置,避免遗漏的情况。
启发:
聊了这么多,那我们这种类似场景的代码应该怎么写?
既然主动写入流会解除@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-

