Skip to content

Commit 78fc5bb

Browse files
committed
Don't throw NPE when serving webjar directories
Prior to this change, serving resources with ResourceHttpRequestHandler could result in NPE when requesting an existing folder located in a JAR. This commit swallows those exceptions, as it is not possible to foresee those cases without reading the actual resource. This result in a HTTP 200 response with a zero Content-Length instead of a HTTP 500 internal exception. Issue: SPR-13620
1 parent a879897 commit 78fc5bb

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,9 @@ protected void writeContent(HttpServletResponse response, Resource resource) thr
410410
try {
411411
StreamUtils.copy(in, response.getOutputStream());
412412
}
413+
catch (NullPointerException ex) {
414+
// ignore, see SPR-13620
415+
}
413416
finally {
414417
try {
415418
in.close();

spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,20 @@ public void writeContentNotClosingInputStream() throws Exception {
310310
assertEquals(0, this.response.getContentLength());
311311
}
312312

313+
// SPR-13620
314+
@Test
315+
public void writeContentInputStreamThrowingNullPointerException() throws Exception {
316+
Resource resource = mock(Resource.class);
317+
InputStream in = mock(InputStream.class);
318+
given(resource.getInputStream()).willReturn(in);
319+
given(in.read(any())).willThrow(NullPointerException.class);
320+
321+
this.handler.writeContent(this.response, resource);
322+
323+
assertEquals(200, this.response.getStatus());
324+
assertEquals(0, this.response.getContentLength());
325+
}
326+
313327

314328
private long headerAsLong(String responseHeaderName) {
315329
return Long.valueOf(this.response.getHeader(responseHeaderName));

0 commit comments

Comments
 (0)