用于下载的弹簧控制器中返回类型的意义是什么。请考虑以下用例:
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返回类型看起来像下面那个
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
答案 0 :(得分:2)
标记方法为void
没什么不好的。您正在通过HttpServletResponse
处理下载操作。
有人建议FileSystemResource
更清洁但考虑到例如在某些情况下,您需要将数据转发到其他地方,以便在其他地方撰写报告。
同样 Spring 可让您轻松处理异常,即使控制器中的返回类型为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
}
}
的更多信息