问题描述
我正在使用Spring boot嵌入式tomcat发布休息服务.
I'm using Spring boot embedded tomcat for publishing rest service.
春季启动版本使用最新的"1.3.6.RELEASE"
Spring boot version used latest "1.3.6.RELEASE"
我要求将application/json发布请求的大小限制为10KB.
I have requirement to limit the application/json post request size to 10KB.
厌倦了此解决方案,但无法正常工作,在Spring Boot中增加HTTP Post maxPostSize
Tired this solution but not working,Increase HTTP Post maxPostSize in Spring Boot
请帮助.
谢谢,阿伦.
推荐答案
配置最大帖子大小仅适用于Content-Type
为multipart/form-data
或application/x-www-form-urlencoded
的请求. Tomcat中没有开箱即用的机制来限制任何其他内容类型的请求的请求主体的大小,因此您必须编写一些代码.
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.
您可以使用过滤器限制内容长度.例如,将以下类添加到您的Spring Boot应用程序将拒绝与application/json
兼容的Content-Type
和10000以上的Content-Length
的请求:
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))));
}
}
请注意,如果没有Content-Length
标头超过10000个字节(例如,使用分块编码的标头),此过滤器将不会拒绝请求.
Note that this filter won't reject requests without a Content-Length
header that exceed 10000 bytes, for example one that uses chunked encoding.
这篇关于Spring Boot嵌入式Tomcat“应用程序/json"要求后限制为10KB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!