我正在使用 Spring boot 嵌入式 tomcat 发布休息服务。
Spring Boot 版本使用最新的“1.3.6.RELEASE”
我要求将 application/json post 请求大小限制为 10KB。
厌倦了这个解决方案但没有工作, Increase HTTP Post maxPostSize in Spring Boot
请帮忙。
谢谢, 阿伦。
最佳答案
配置最大帖子大小仅适用于 Content-Type
为 multipart/form-data
或 application/x-www-form-urlencoded 的请求
。 Tomcat 中没有开箱即用的机制来限制具有任何其他内容类型的请求的请求正文的大小,因此您必须编写一些代码。
您可以使用过滤器限制内容长度。例如,将以下类添加到您的 Spring Boot 应用程序将拒绝具有与 application/json
兼容的 Content-Type
和 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))));
}
}
请注意,此过滤器不会拒绝没有超过 10000 字节的 Content-Length
header 的请求,例如使用分块编码的请求。
关于json - Spring boot Embedded Tomcat "application/json"post请求限制为10KB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38607159/