views:

89

answers:

2

I need to determine if an image exists in a JSP tag so I can display a default if it doesn't exist. What is the best way to access the War root so that I can check to see if the image exists? Or is there a better solution?

+1  A: 

The ServletContext method getResource can be used for features like this. If the resource (the image) doesn't exist, this method returns null. In that case, a default image can be displayed.

Note that the URL this method returns is not the URL to use as the "src" attribute in an <img> tag. It is most likely a file: or jar: protocol URL that wouldn't make sense on another host. In this application, its only tested to see if it is null, and not actually by the JSP.

erickson
The only problem is that the web framework we are forced to use, hides any access to the ServletContext.
Joshua
Really? What framework? Sensible frameworks still provide access to application, session, and request scopes by wrapping them in some sort of abstraction. There are kludges you can do if your framework is really that limited.
erickson
Notice the word "forced". Sensible frameworks are not forced on developers. Developers choose them because they are sensible.
Joshua
+1  A: 

Also note there is no guarantee that the web container has exploded your WAR file, so you should avoid peeking at the filesystem.

Would it be an option to generate the list of available images at deployment time?

Thorbjørn Ravn Andersen
The end goal is to just see if an image exists otherwise display a default so this would work.
Joshua