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
2009-04-24 16:59:31
The only problem is that the web framework we are forced to use, hides any access to the ServletContext.
Joshua
2009-04-24 22:12:41
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
2009-04-24 22:28:46
Notice the word "forced". Sensible frameworks are not forced on developers. Developers choose them because they are sensible.
Joshua
2009-04-27 14:39:28
+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
2009-04-24 18:36:06
The end goal is to just see if an image exists otherwise display a default so this would work.
Joshua
2009-04-24 22:11:43