Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

rest - Spring boot Embedded Tomcat "application/json" post request restriction to 10KB

I'm using Spring boot embedded tomcat for publishing rest service.

Spring boot version used latest "1.3.6.RELEASE"

I have requirement to limit the application/json post request size to 10KB.

Tired this solution but not working, Increase HTTP Post maxPostSize in Spring Boot

Please help.

Thanks, Arun.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...