java - 在 Spring Web MVC 中下载或重定向错误消息到另一个 Controller 操作

标签 java spring-mvc redirect download spring-web

想法:我有一个 Spring web MVC 操作应该完成这些任务中的一个或两个:

  • 从远程服务器下载文件并将输入流写入响应输出流
  • 或者捕获下载异常,设置多个错误消息之一并重定向到/addresses 页面。地址页会显示错误

问题:如果出现问题,Spring 无法下载文件和重定向 - 不知何故 flash 属性不起作用,因为在重定向中丢失了:

@ResponseBody
@RequestMapping(value = "/download/{fileaddress}", method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "fileaddress") String fileaddress) throws Exception
{
    if(fileaddress != null && fileaddress.length() > 0)
    {
        try
        {
            // Get the remove file based on the fileaddress
            RemoteFile remotefile = new RemoteFile(fileaddress);

            // Set the input stream
            InputStream inputstream = remotefile.getInputStream();

            // Write the input stream to the output stream or throw an exception
            Utils.writeTo(inputstream, response.getOutputStream());
        }
        catch(MyExceptionA)
        {
            // TODO: Define error message a and pass it to /addresses
            // PROBLEM: Flash attributes that contain all critical error information don't work
            response.sendRedirect(request.getContextPath() + "/addresses");
        }
        catch(MyExceptionB)
        {
            // TODO: Add another error message and redirect
            response.sendRedirect(request.getContextPath() + "/addresses");
        }
        catch(MyExceptionC)
        {
            // TODO: Add another error message and redirect
            response.sendRedirect(request.getContextPath() + "/addresses");
        }
        catch(MyExceptionN)
        {
            // TODO: Add another error message and redirect
            response.sendRedirect(request.getContextPath() + "/addresses");
        }
    }
    else
    {
        // TODO: Add error message
        response.sendRedirect(request.getContextPath() + "/addresses");
    }
}

/addresses的JSP页面:

<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<tags:index>
    <jsp:attribute name="content">
        <core:if test="${not empty error}">
            <div class="alert alert-danger">
                <p>${error}</p>
            </div>
        </core:if>
        <p>Page under construction!</p>
    </jsp:attribute>
</tags:index>

问题:我如何能够在/addresses 站点中显示错误消息(例如简单字符串)?使用不同的 URL 参数(error=errora、error=errorb ...)是一个巨大的痛苦,如果有多种错误类型并将错误消息作为 GET 参数传递看起来不专业并且是编码问题的根源。

最佳答案

您需要的是 RedirectAttributesModel 的一个特例, Controller 可以使用它来为重定向场景选择属性。 因此,对于一个工作示例,请参见下面的代码:

@ResponseBody
@RequestMapping(value = "/download/{fileaddress}", method = RequestMethod.GET)
public Object download(@PathVariable(value = "fileaddress") String fileaddress, RedirectAttributes redirectAttrs) throws Exception {
    if(StringUtils.hasText(fileaddress)){
        try{
            // Get the remove file based on the fileaddress
            RemoteFile remotefile = new RemoteFile(fileaddress);

            // Set the input stream
            InputStream inputstream = remotefile.getInputStream();
            // asume that it was a PDF file
            HttpHeaders responseHeaders = new HttpHeaders();
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            responseHeaders.setContentLength(contentLengthOfStream);
            responseHeaders.setContentType(MediaType.valueOf("application/pdf"));
            return new ResponseEntity<InputStreamResource> (inputStreamResource,
                                       responseHeaders,
                                       HttpStatus.OK);
         } catch (MyExceptionA | MyExceptionB | MyExceptionC | MyExceptionD ex) {
           redirectAttrs.addFlashAttribute("error", ex.getMessage());
         }        
    } else {
        redirectAttrs.addFlashAttribute("error", "File name is required");
    }
    return "redirect:/addresses";
}

关于java - 在 Spring Web MVC 中下载或重定向错误消息到另一个 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617937/

相关文章:

java - 检查数据库中是否存在表

java - 如果配置中提供了默认值,Quarkus >= 0.18.0 将无法构建

java - Spring Security hasRole() 不起作用

java - Spring Boot 自定义 ErrorAttributes http 状态未设置为响应

python - Django - 表单提交时没有重定向

php - 重定向,但隐藏推荐人

php - 使用wordpress重写url时如何避免重定向

java - 如何在单击按钮时打开框架

java - 如何避免在我的java bean中使用Spring注释并仅在配置类中使用它们?

javascript - 在 javascript 中使用 Spring 变量