diff --git a/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java b/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java index e747aebe91f..4649a58e0a3 100644 --- a/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java +++ b/spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java @@ -85,7 +85,9 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper { /** * Create a new ContentCachingRequestWrapper for the given servlet request. * @param request the original servlet request - * @param contentCacheLimit the maximum number of bytes to cache per request + * @param contentCacheLimit the maximum number of bytes to cache per request; + * no limit is set if the value is 0 or less. It is recommended to set a + * concrete limit in order to avoid using too much memory. * @since 4.3.6 * @see #handleContentOverflow(int) */ @@ -93,12 +95,12 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper { super(request); int contentLength = request.getContentLength(); if (contentLength > 0) { - this.cachedContent = new FastByteArrayOutputStream(Math.min(contentLength, contentCacheLimit)); + this.cachedContent = new FastByteArrayOutputStream((contentCacheLimit > 0 ? Math.min(contentLength, contentCacheLimit) : contentLength)); } else { this.cachedContent = new FastByteArrayOutputStream(); } - this.contentCacheLimit = contentCacheLimit; + this.contentCacheLimit = (contentCacheLimit > 0 ? contentCacheLimit : null); } diff --git a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java index 415a5df7372..f9e67741e4d 100644 --- a/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/ContentCachingRequestWrapperTests.java @@ -74,6 +74,14 @@ class ContentCachingRequestWrapperTests { assertThat(wrapper.getContentAsString()).isEqualTo(new String(response, CHARSET)); } + @Test + void cachedContentToByteArrayWithoutLimit() throws Exception { + ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(createGetRequest("Hello World"), 0); + byte[] response = wrapper.getInputStream().readAllBytes(); + assertThat(response).isEqualTo("Hello World".getBytes(CHARSET)); + assertThat(wrapper.getContentAsByteArray()).isEqualTo("Hello World".getBytes(CHARSET)); + } + @Test void cachedContentToByteArrayWithLimit() throws Exception { ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(createGetRequest("Hello World"), CONTENT_CACHE_LIMIT);