-1

I'm using a standard maven archetype of webapp, so I put my images folder under src/main/resources directory and in the war package it goes under WEB-INF/classes/ directory.

My project tree is in the following image enter image description here

So the images dir is in the classpath and i load it via getResource

final String path ="/resources/images/disegno.svg";
URL imagePath = this.getClass().getClassLoader().getResource(path);

but i get

Could not complete request
java.lang.NullPointerException

when declaring path Also in .jsp, I try to access the image in this way:

<img src="<%=request.getContextPath() %>/WEB-INF/classes/images/disegno.svg"/>

but no image is displayed, even if it links to

http://localhost:8080/svgTest/WEB-INF/classes/images/disegno.svg

I cannot understand how maven works in this situation, and cannot find a complete guide, because everywhere all looks so easy, so I don't know which error i'm doing...

MarioC
  • 2,934
  • 15
  • 59
  • 111
  • Possible duplicate of http://stackoverflow.com/questions/3803326/this-getclass-getclassloader-getresource-and-nullpointerexception? – ma cılay Mar 01 '16 at 22:03

1 Answers1

1

You're making 3 mistakes.

First: ClassLoader.getResource() expects a path that does NOT start with a /.

Second: what is under src/main/resources in the source project goes at the root of the classpath. There is no resources package, as your screenshot of WEB-INF/classes shows. So your path should be

this.getClass().getClassLoader().getResource("images/disegno.svg")

Third: by design, everything undex WEB-INF is not accessible from the browser. Everything out of WEB-INF is. So if you want the browser to be able to download your image, it should be in the src/main/webapp folder, not in src/main/resources. Of cource, once it's there, you won't be able to load it with the ClassLoader anymore, since it won't be in the classpath anymore. If you need to load it in addition to make it directly available to the browser, then use ServletContext.getResource().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255