java - 当metod返回ResponseEntiry时如何返回ModelandView抛出错误?
问题描述
我有以下方法
@GetMapping("/{fileName}")
public Object downloadFile(@PathVariable String fileName) {
// Load file from database
errors.clear();
DBFile dbFile;
try {
dbFile = dBFileStorageService.getFileByName(fileName);
} catch (MyFileNotFoundException ex) {
logger.info("File has not been found.");
errors.add(ex.getMessage());
return new ModelAndView("redirect:/");
}
logger.info("Delivering file");
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(dbFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
.body(new ByteArrayResource(dbFile.getData()));
}
ResponseEntity<Resource>
如果可以返回文件或其他方式,我想返回而不是返回对象ModelAndView("redirect:/")
。
我试过:
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/member/uploadImage");
return new ResponseEntity<>(headers,HttpStatus.FOUND);
但是我收到的消息不是重定向,而是我尝试下载的文件已损坏。总结一下,我想将方法签名更改为:
public ResponseEntiry<Resource> downloadFile(@PathVariable String fileName)
解决方案
关于您通过 ResponseEntity 返回文件的第一个问题已在此处得到解答: Return file from Spring @Controller has OutputStream
同意@chrylis,因为他建议您在发生异常时采取的最佳方法是抛出异常并使用方法注释在srind@ControllerAdvice
类中处理它。@ExceptionHandler
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409 or according to your need any code
@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
System.out.println("handling exception here!!!");
ModelAndView mv = new ModelAndView();
mv.setViewName("errorView");
mv.addObject("ERROR", "ERROR OCCURRED REDIRECTED "+ex.getMessage());
return mv;
}
}
官方文档。
推荐阅读
- mongodb - 有没有办法为此查询使用聚合管道方法
- asp.net-web-api2 - Web API 2:如果控制器方法同时被 [HttpPost] 和 [HttpGet] 重载,[FromBody] 控制器方法参数是否可以是可选的?
- python - 字符串清理
- xml - Google 表格 ImportXML XPath 返回 #N/A
- powershell - 退出“拖尾”文件的 Get-Content 命令的 Powershell 脚本
- javascript - 如何在反应中实现平滑的响应视差效果?
- javascript - 是否有事件或方法可以知道 Chrome 扩展程序何时在“扩展程序”页面中打开或关闭?
- python - 如何摆脱字符串列表中的单词
- reactjs - 如何配置响应以使用 npm-watch 监视 css 文件的更改
- python - 将系列放置到给定数组