配置最大尺寸后仅适用于有要求Content-Type
的multipart/form-data
或application/x-www-form- urlencoded
。Tomcat中没有开箱即用的机制来限制具有任何其他内容类型的请求的请求主体的大小,因此您必须编写一些代码。
您可以使用过滤器限制内容长度。例如,将以下类添加到您的Spring Boot应用程序将拒绝与Content- Type
兼容application/json
且Content-Length
超过10000 的请求:
@Component
static class ApplicationJsonRequestSizeLimitFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (isApplicationJson(request) && request.getContentLengthLong() > 10000) {
throw new IOException("Request content exceeded limit of 10000 bytes");
}
filterChain.doFilter(request, response);
}
private boolean isApplicationJson(HttpServletRequest httpRequest) {
return (MediaType.APPLICATION_JSON.isCompatibleWith(MediaType
.parseMediaType(httpRequest.getHeader(HttpHeaders.CONTENT_TYPE))));
}
}
请注意,如果Content-Length
标头超过10000个字节(例如,使用分块编码的标头),则此过滤器不会拒绝请求。