什么是undertow
undertow是RedHat(红帽公司)的开源产品,采用java开发,是一款灵活、高性能的web服务器,提供了基于NIO的阻塞/非阻塞式APIs,也是WildFly(原名JBoss AS - JBoss Application Server)的默认web容器。
undertow是springboot默认支持的三种servlet容器之一。 tomcat、jetty、undertow
业务场景: 测试文件上传的时候遇到如下:"Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: io.undertow.server.handlers.form.MultiPartParserDefinition$FileTooLargeException: UT000054: The maximum size 1048576 for an individual file in a multipart request was exceeded" 开发环境: springBoot2.3.2.RELEASE 容器undertow 问题原因: 容器undertow在上传文件时存在一个容易忽略的配置问题: 由于springboot具有几个版本,不同版本对于文件上传最大限制的配置也有所不同。 所以要注意springboot本身的版本,不然会一直报错 在springboot1.3版本中: multipart.maxFileSize 在springboot1.4与springboot1.5版本中: properties:
spring.http.multipart.max-file-size:10MB
spring.http.multipart.max-request-size:50MB
yml:
spring:
http:
multipart:
maxFileSize: 10Mb
maxRequestSize: 50Mb
在springboot2.0版本中: properties:
spring.servlet.multipart.enabled=true # 是否支持多部分上传。
spring.servlet.multipart.max-file-size:10MB # 最大支持文件上传的大小
spring.servlet.multipart.max-request-size:50MB # 支持请求最大文件上传的大小
yml:
spring:
servlet:
multipart:
maxFileSize: 10Mb
maxRequestSize: 50Mb
说明: FileTooLargeException异常判断就是对undertow容器的支持,SpringBoot不会被系统异常拦截机制捕获到,这应该是容器的问题,建议用tomcat。
解决办法: 参考网上的解决问题的办法大致有以下几种:
第一种:使用spring-boot-starter-web的内置Tomcat
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
AI回答:spring-boot-starter-web如何内置Tomcat? 在Spring Boot中,spring-boot-starter-web
是一个模块化依赖(starter),它为开发基于Web的应用程序提供了所有必需的依赖项。当你将 spring-boot-starter-web
添加到项目的 pom.xml
文件时,它会间接引入嵌入式的Tomcat容器作为Servlet容器。通过继承自 spring-boot-starter
和 spring-boot-dependencies
的父POM来管理这些底层依赖版本的。版本是通过父POM中的 <properties>
标签进行集中管理的,因此实际使用的Tomcat版本会根据你使用的Spring Boot starter parent版本动态确定。
第二种:使用全局捕获异常(MaxUploadSizeExceededException)
/**
* 全局异常处理器
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerResolver {
/**
* @Descript 统一处理文件过大问题.
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public R handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.error("上传文件过大 ex={}", e);
return retMsgCode("上传文件过大", 9999);
}
}
第三种:前端进行控制
但是这种方法只是治标不治本,没有从根本上解决问题,而且不符合解决问题的一般步骤。