Configuring the max post size only applies to requests with a Content-Type
of multipart/form-data
or application/x-www-form-urlencoded
. There's no mechanism available out of the box in Tomcat to limit the size of a request body for requests with any other content type so you'll have to write some code.
You could limit the content length using a filter. For example, adding the following class to your Spring Boot application will reject an request with a Content-Type
that is compatible with application/json
and a Content-Length
over 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))));
}
}
Note that this filter won't reject requests without a Content-Length
header that exceed 10000 bytes, for example one that uses chunked encoding.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…