gpt4 book ai didi

java - spring文件下载 Controller 中返回类型的意义

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:22:24 26 4
gpt4 key购买 nike

用于下载的 Spring Controller 中返回类型的意义是什么。请考虑以下用例:

public ModelAndView execute(final HttpServletRequest request, final HttpServletResponse response) {
try {
//some code.
} catch {
//handle the exception and build a error model and view. This model and view
//gives a lot of freedom for error handling in case of download fails on the
//same page without change in URL(enabling refresh of the same page again
//and again)
return modelAndView;
}
return null;
}

但通常我见过具有 void 返回类型的 Controller ,如下所示

    public void execute(final HttpServletRequest request, final HttpServletResponse response) {
try {
//some code.
} catch {
//handle the exception but you cannot display the error with out leaving the same page. Error embedding is not possible without changing the URL.
}
}

我有两个问题:

a) 一种方法相对于另一种方法的缺点是什么?我发现第一个服务的用例比第二个多。

b)返回 null 而不是 ModelAndView 有什么缺点吗?

引用资料:

Downloading a file from spring controllers

Error handling by redirection in spring download file controller

最佳答案

将方法标记为 void 没什么不好。您正在通过 HttpServletResponse 处理下载操作。有人建议 FileSystemResource 更干净,但要考虑到这一点,例如在某些情况下,您需要将数据转发到其他地方,以便在其他地方撰写报告。

此外,Spring 让您轻松处理异常,即使您在 Controller 中的返回类型是 void:

@RequestMapping(value = "/pdf-report/{id}.pdf", method = RequestMethod.GET)
public void downloadPdfReport(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {

//supposed logic here
//if we are failing here then
throw new UserFriendlyException("Cannot produce data");
}

然后 ControllerAdvice 发挥作用:

@ControllerAdvice
public class ExceptionControllerAdvice {

@ExceptionHandler(UserFriendlyException.class)
public ModelAndView handleUserFriendlyException(UserFriendlyException ex) {
//handle here your custom error page
}
}

更多信息来自 Spring resources

关于java - spring文件下载 Controller 中返回类型的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27364744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com