简体   繁体   中英

How limit max size request in Spring Web Services?

I have got a Spring Boot 2 application with Spring Web Services and I try to limit max size of incoming requests. I've tried to use the following properties, but it doesn't work.

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

Do you know any working solution to limit max size of incoming requests in Spring Boot 2 application with Spring Web Services? In the Spring Web Services documentation there is information that Spring Web Services provides a transport based on Sun's JRE 1.6 HTTP server. Maybe it's a problem?

Add this Bean with your application and set your required size (Currently 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
                    }
                );
            }
        };
    }

Finally, I've decided to create a filter.

@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);
            }
        }
        ...
    }
    ...
}

Is it an HTTP POST request that you are using?

Because

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

works perfectly

GET for large requests is not the best idea. If you really need then you can try server.max-http-header-size

All 3 parameters verified on tomcat 8.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM