使用弹簧启动处理MultipartException并显示错误页面 [英] Handling MultipartException with Spring Boot and display error page

查看:375
本文介绍了使用弹簧启动处理MultipartException并显示错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的文件上传设置与Spring Boot。
我想知道当超过最大文件大小时是否有一个简单的方法显示错误页面。



我已经上传了一个非常简单的例子我试图在github上实现



基本上,这个想法是在全局Spring异常处理程序中捕获MultipartException:

  @ControllerAdvice 
public class UploadExceptionHandler {

@ExceptionHandler(MultipartException.class)
public ModelAndView handleError(MultipartException异常){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(error,exception.getMessage());
modelAndView.setViewName(uploadPage);
return modelAndView;
}
}

处理文件上传的控制器非常简单:

  @RequestMapping(/)
public String uploadPage(){
returnuploadPage;
}

@RequestMapping(value =/,method = RequestMethod.POST)
public String onUpload(@RequestParam MultipartFile文件){
System.out。的println(file.getOriginalFilename());
returnuploadPage;
}

而且与它相关联的uploadPage.html百里香模板也是如此:

 <!DOCTYPE html> 
< html xmlns:th =http://www.thymeleaf.org>
< head lang =en>
< title>上传< / title>
< / head>
< body>

< div style =color:redth:text =$ {error}th:if =$ {error}>
上传时出错
< / div>

< form th:action =@ {/}method =postenctype =multipart / form-data>
< input type =fileid =filename =file/>
< button type =submitname =save> Submit< / button>
< / form>
< / body>
< / html>

这个想法是在文件太大时在同一个上传页面上显示错误消息。 / p>

我的理解是,可以配置Spring的MultipartResolver来懒洋洋地解决异常,并能够在Spring的级别(MVC异常处理程序)捕获这些异常,但是这个代码似乎不帮助:

  @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
public StandardServletMultipartResolver multipartResolver(){
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(true);
return multipartResolver;
}

所以在我采取极端措施,如过滤器或扩展MultipartResolver ..



您是否知道使用Spring MVC处理这些异常的干净方法?



答案



感谢@ rossen-stoyanchev。
这是我最后做的:

  @RequestMapping(uploadError)
public ModelAndView onUploadError (HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView(uploadPage);
modelAndView.addObject(error,request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE));
return modelAndView;
}

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
返回容器 - > container.addErrorPages(new ErrorPage(MultipartException.class,/ uploadError));
}

像一个魅力一样工作,感觉像一个优雅的解决方案。
如果有人感兴趣,我更新了github上的项目。
非常感谢!

解决方案

多处理器请求解析在选择处理程序之前发生,因此没有@Controller,因此没有@ControllerAdvice可以说了。您可以使用ErrorController(请参阅 http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-error-处理)。



BTW你不需要@RequestParam。参数类型是MultipartFile就足够了。


I have a very simple file upload set up with Spring Boot. I was wondering if there was an easy way to display an error page when the maximum file size is exceeded.

I have uploaded a very simple example of what I'm trying to achieve on github.

Basically, the idea is to catch the MultipartException in a global Spring exception handler:

@ControllerAdvice
public class UploadExceptionHandler {

  @ExceptionHandler(MultipartException.class)
  public ModelAndView handleError(MultipartException exception) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("error", exception.getMessage());
    modelAndView.setViewName("uploadPage");
    return modelAndView;
  }
}

The controller which handles the file upload is really simple:

@RequestMapping("/")
public String uploadPage() {
    return "uploadPage";
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public String onUpload(@RequestParam MultipartFile file) {
    System.out.println(file.getOriginalFilename());
    return "uploadPage";
}

And the uploadPage.html thymeleaf template associated with it too:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <title>Upload</title>
</head>
<body>

<div style="color: red" th:text="${error}" th:if="${error}">
    Error during upload
</div>

<form th:action="@{/}" method="post" enctype="multipart/form-data">
  <input type="file" id="file" name="file"/>
  <button type="submit" name="save">Submit</button>
</form>
</body>
</html>

The idea is to display an error message in the same upload page when the file is too big.

It was my understanding that one would configure Spring's MultipartResolver to resolve exceptions lazily and be able to catch those exceptions at Spring's level (MVC exception handlers) but this code does not seem to help:

@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
public StandardServletMultipartResolver multipartResolver() {
    StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
    multipartResolver.setResolveLazily(true);
    return multipartResolver;
}

So before I resort to extreme measures like a filter or extending the MultipartResolver...

Do you know a clean way to handle those exceptions with Spring MVC?

Answer

Thanks to @rossen-stoyanchev. Here is what I ended up doing:

@RequestMapping("uploadError")
public ModelAndView onUploadError(HttpServletRequest request) {
    ModelAndView modelAndView = new ModelAndView("uploadPage");
    modelAndView.addObject("error", request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE));
    return modelAndView;
}

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return container -> container.addErrorPages(new ErrorPage(MultipartException.class, "/uploadError"));
}

Works like a charm and feels like an elegant solution. I updated the project on github if someone is interested. Many thanks!

解决方案

Multipart request parsing happens before a handler is selected and hence there is no @Controller and therefore no @ControllerAdvice to speak of yet. You can use an ErrorController (see http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-error-handling) for that.

BTW you don't need @RequestParam. It's enough that the argument type is MultipartFile.

这篇关于使用弹簧启动处理MultipartException并显示错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆