java - spring 下载文件 Controller 中重定向的错误处理

标签 java spring jsp spring-mvc

This问题很好地解释了如何在 Spring 编写下载文件 Controller 。 This问题很好地解释了不能使用 response.sendRedirect() 发送 Post 请求

我希望用户被重定向到同一页面,并显示有关导致文件下载错误的原因的错误。这是工作流程

  1. 用户点击 www.abc.com/index [ Controller 有映射/index.jsp 并返回 ModelAndView]
  2. 在此页面上,我们有一个文件下载,其 URL 为 www.abc.com/download?resource_id=123。 [ Controller 有映射/下载并返回无效]
  3. 当文件下载出现错误时,应将用户重定向到 www.abc.com/index 并显示一些错误。
  4. 当文件下载没有错误时,用户停留在同一页面并出现文件下载对话框。

以下为转发片段:

@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/

相关文章:

java - TextView 不会将我从登录重定向到我的注册 Activity

java - 在 Spring Security 中登录后点击登录网址

java - 如何从通用类创建 BeanPropertyRowMapper?

项目之间共享的 Java 域对象

java - 在liferay processAction方法中转发到JSp文件

Java Web应用程序安全理念

java - 使用 tokenizer 读取一行

java - 如何在java中传递 '<ClassName>.class'作为参数?

java - JPA 在 Spring 中到底是如何工作的?一些疑问

mysql - 当我尝试使用 mysql 中的数据库创建矩阵时,我在 JSP 文件中遇到 NullPointerException