Skip to content

Commit 9334fab

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 323fa85 commit 9334fab

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

+3
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,9 @@ protected void writeContent(HttpServletResponse response, Resource resource) thr
460460
try {
461461
StreamUtils.copy(in, response.getOutputStream());
462462
}
463+
catch (NullPointerException ex) {
464+
// ignore, see SPR-13620
465+
}
463466
finally {
464467
try {
465468
in.close();

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

+14
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,20 @@ public void writeContentNotClosingInputStream() throws Exception {
478478
assertEquals(0, this.response.getContentLength());
479479
}
480480

481+
// SPR-13620
482+
@Test
483+
public void writeContentInputStreamThrowingNullPointerException() throws Exception {
484+
Resource resource = mock(Resource.class);
485+
InputStream in = mock(InputStream.class);
486+
given(resource.getInputStream()).willReturn(in);
487+
given(in.read(any())).willThrow(NullPointerException.class);
488+
489+
this.handler.writeContent(this.response, resource);
490+
491+
assertEquals(200, this.response.getStatus());
492+
assertEquals(0, this.response.getContentLength());
493+
}
494+
481495

482496
private long dateHeaderAsLong(String responseHeaderName) throws Exception {
483497
return dateFormat.parse(this.response.getHeader(responseHeaderName)).getTime();

0 commit comments

Comments
 (0)