ServletContext getResource not working

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-06-09T14:23:16Z Indexed on 2010/06/09 14:32 UTC
Read the original article Hit count: 394

Filed under:
|
|

I'm trying to use ServletContext.getResource to retrieve a java.net.url reference to an image file (which I will then include in a PDF library using iText). When I use ServletContext.getRealPath("picture.jpg"), I get back a string URL. However, getResource always returns null.

Example 1:

String picture = ServletContext.getRealPath("picture.jpg");
// picture contains a non-null String with the correct path
URL pictureURL = ServletContext.getResource(picture);
// pictureURL is always null

Example 2:

URL pictureURL = ServletContext.getResource("picture.jpg");
// pictureURL is always null

So what is the correct way to build a java.net.URL object pointing to a file in my webapps folder? Why does getRealPath work but not getResource?

In case it helps at all, here is my folder structure

webapps -> mySite -> picture.jpg

Does my picture need to be stored in either WEB-INF or WEB-INF/classes to be read by getResource?

© Stack Overflow or respective owner

Related posts about java

Related posts about servlets