SpringBoot2.0.0新版本内嵌Tomcat配置
前言
项目组的同事遇到一个问题,在提交表单数据的时候后台抛出一个异常,异常信息如下:
java.lang.IllegalStateException: More than the maximum number of request parameters (GET plus POST) for a single request ([10,000]) were detected. Any parameters beyond this limit have been ignored. To change this limit, set the maxParameterCount attribute on the Connector.
以前使用外部Tomcat部署项目的时候,可以通过修改server.xml文件中的Connector节点maxParameterCount属性值解决这个问题。
<Connector port=“8080” redirectPort=“8443” protocol=“HTTP/1.1”
maxParameterCount="-1"
/>
因为SpringBoot使用的是内嵌的Tomcat,无法配置server.xml。经过查看相关API文档并没有发现可以直接在配置文件中配置maxParameterCount属性,那么我们就在代码中进行配置,在SpringBoot的API文档中讲解了通过实现WebServerFactoryCustomizer接口可以对Tomcat进行相关配置。
参考
解决方法
创建一个类并实现WebServerFactoryCustomizer接口的customize方法。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
/**
* 自定义Tomcat容器配置类
*
*/
@Component
public class MyTomcatWebServerFactoryCustomizer
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
public static final int DEFAULT_MAX_PARAMETER_COUNT = 10000;
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 单次请求参数最大限制数
*/
@Value("${server.tomcat.maxParameterCount}")
private int maxParameterCount = DEFAULT_MAX_PARAMETER_COUNT;
@Override
public void customize(TomcatServletWebServerFactory factory) {
if (logger.isDebugEnabled()) {
logger.debug("MyTomcatWebServerFactoryCustomizer customize");
}
PropertyMapper propertyMapper = PropertyMapper.get();
propertyMapper.from(this::getMaxParameterCount)
.when((maxParameterCount) -> maxParameterCount != DEFAULT_MAX_PARAMETER_COUNT)
.to((maxParameterCount) -> customizerMaxParameterCount(factory, maxParameterCount));
}
/**
* 配置内置Tomcat单次请求参数限制
*
* @param factory
* @param maxParameterCount
*/
private void customizerMaxParameterCount(TomcatServletWebServerFactory factory,
int maxParameterCount) {
factory.addConnectorCustomizers(
connector -> connector.setMaxParameterCount(maxParameterCount));
}
public void setMaxParameterCount(int maxParameterCount) {
this.maxParameterCount = maxParameterCount;
}
public int getMaxParameterCount() {
return maxParameterCount;
}
}