Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServletContext getResource not working

Tags:

java

servlets

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?

like image 776
David Avatar asked Jun 09 '10 14:06

David


People also ask

What is the scope of ServletContext?

Context/Application Scope - javax. servlet. ServletContext Parameters/attributes within the application scope will be available to all requests and sessions. The Context/Application object is available in a JSP page as an implicit object called application.

What is getRealPath of ServletContext?

Introduction. The ServletContext#getRealPath() is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path. The "/" represents the web content root.

What is ServletContext in java?

public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.


2 Answers

Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.

So you must provide the context-relative full path. For example:

URL pictureURL = servletContext.getResource("/images/picture.jpg");

(note the lower-cased servletContext variable)

like image 82
Bozho Avatar answered Sep 28 '22 18:09

Bozho


getRealPath() provides the operating specific absolute path of a resource, while getResource() accepts a path relative to the context directory, and the parameter must begin with a "/". Try ServletContext.getResource ("/picture.jpg") instead.

Doc: getResource

like image 30
Greg Case Avatar answered Sep 28 '22 16:09

Greg Case