【问题标题】:How limit max size request in Spring Web Services?如何限制 Spring Web 服务中的最大大小请求?
【发布时间】:2020-10-22 18:34:40
【问题描述】:

我有一个带有 Spring Web Services 的 Spring Boot 2 应用程序,我尝试限制传入请求的最大大小。我尝试使用以下属性,但它不起作用。

server.tomcat.max-http-form-post-size
spring.servlet.multipart.max-request-size
spring.servlet.multipart.max-file-size

您知道使用 Spring Web 服务限制 Spring Boot 2 应用程序中传入请求的最大大小的任何可行解决方案吗? 在 Spring Web Services documentation 中有信息表明 Spring Web Services 提供了基于 Sun 的 JRE 1.6 HTTP 服务器的传输。也许是个问题?

【问题讨论】:

标签: java spring spring-boot tomcat spring-ws


【解决方案1】:

在您的应用程序中添加此 Bean 并设置您所需的大小(当前为 10 MB)

// Set maxPostSize of embedded tomcat server to 10 MB (default is 2 MB, not large enough to support file uploads > 1.5 MB)
    @Bean
    EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
        return (ConfigurableEmbeddedServletContainer container) -> {
            if (container instanceof TomcatEmbeddedServletContainerFactory) {
                TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
                tomcat.addConnectorCustomizers(
                    (connector) -> {
                        connector.setMaxPostSize(10000000); // 10 MB
                    }
                );
            }
        };
    }

【讨论】:

  • 这是 Spring Boot 2 应用程序,所以我尝试使用 TomcatServletWebServerFactory,但它仍然无法正常工作,并且没有过滤掉大尺寸请求。 @Component public class CustomContainer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> { @Override public void customize(final TomcatServletWebServerFactory factory) { factory.addConnectorCustomizers(connector -> connector.setMaxPostSize(1000000)); } }
  • @MateuszZieliński 你能尝试把它自己放入 springbootapplication 类吗?
【解决方案2】:

最后,我决定创建一个过滤器。

@Bean
public Filter maxRequestSizeFilter() {
    return new Filter() {
        @Override
        public void init(final FilterConfig filterConfig) {

        }

        @Override
        public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
            final FilterChain filterChain) throws IOException, ServletException {
            final long size = servletRequest.getContentLengthLong();
            if (size > maxRequestSizeInBytes) {
                ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
            } else {
                    filterChain.doFilter(servletRequest, servletResponse);
            }
        }
        ...
    }
    ...
}

【讨论】:

    【解决方案3】:

    您使用的是 HTTP POST 请求吗?

    因为

    • spring.servlet.multipart.max-request-size
    • spring.servlet.multipart.max-file-size

    完美运行

    对于大型请求,GET 不是最好的主意。如果你真的需要那么你可以试试 server.max-http-header-size

    在 tomcat 8.5 上验证所有 3 个参数

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 2021-12-15
      • 2010-10-06
      • 2015-01-08
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多