This问题很好地解释了如何在 Spring 编写下载文件 Controller 。 This问题很好地解释了不能使用 response.sendRedirect() 发送 Post 请求
我希望用户被重定向到同一页面,并显示有关导致文件下载错误的原因的错误。这是工作流程
- 用户点击 www.abc.com/index [ Controller 有映射/index.jsp 并返回 ModelAndView]
- 在此页面上,我们有一个文件下载,其 URL 为 www.abc.com/download?resource_id=123。 [ Controller 有映射/下载并返回无效]
- 当文件下载出现错误时,应将用户重定向到 www.abc.com/index 并显示一些错误。
- 当文件下载没有错误时,用户停留在同一页面并出现文件下载对话框。
以下为转发片段:
@RequestMapping(/download)
public void execute(@RequestParam(value = "resource_id" required = true) final String resource, final HttpServletRequest request, final HttpServletResponse response) {
try {
//some processing
} catch {
RequestDispatcher dispatcher = request.getRequestDispatcher("/index" + "?is_downloaded=false");
dispatcher.forward(request, response)
}
}
@RequestMapping(/index)
public void execute(@RequestParam(value = "is_downloaded" required = false) final String isDownloaded, final HttpServletRequest request) {
//do stuff here
}
第 3 步是问题所在。
- 使用转发将 URL 更改为错误报告的下载 URL。
- 使用重定向作为带有隐藏参数的 response.sendRedirect() 是不可能的,根本不会修改 URL。
- 使用带有隐藏参数的 response.sendRedirect() 重定向,并在 URL 末尾引入“?is_downloaded=false”
谁能告诉我解决方法。
最佳答案
我一直有类似的问题,并用下面的代码解决了它。
我的 Controller 中有以下异常处理程序。如果出现错误,这会处理重定向和错误消息。
@ExceptionHandler(FileNotFoundException.class)
public ModelAndView exceptionHandler(Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("rescues/general");
modelAndView.addObject("message", ex.getMessage());
return modelAndView;
}
这是请求映射
@RequestMapping(value = "s3Download.request", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> download(@RequestParam(value = "s3key") String s3Key)
throws IOException {
HttpHeaders responseHeaders = new HttpHeaders();
InputStreamResource inputStreamResource = s3DownloadService.getS3File(s3Key, responseHeaders);
return new ResponseEntity<>(inputStreamResource, responseHeaders, HttpStatus.OK);
}
如果文件在您的本地服务器上,您可以使用 FileSystemResource 代替 InputStreamResource。
服务层负责在 HttpHeaders 对象上设置响应 header 值
responseHeaders.setContentType(MediaType.parseMediaType(objectMetaData.getContentType()));
responseHeaders.setContentLength(objectMetaData.getContentLength());
responseHeaders.setContentDispositionFormData("attachment", fileName);
关于java - spring 下载文件 Controller 中重定向的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324092/