Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically reading static resources from my java webapp [duplicate]

Tags:

java

servlets

war

I currently have a bunch of images in my .war file like this.

WAR-ROOT
  -WEB-INF
  -IMAGES
    -image1.jpg
    -image2.jpg
  -index.html

When I generate html via my servlets/jsp/etc I can simple link to

http://host/contextroot/IMAGES/image1.jpg

and

http://host/contextroot/IMAGES/image1.jpg

Not I am writing a servlet that needs to get a filesystem reference to these images (to render out a composite .pdf file in this case). Does anybody have a suggestion for how to get a filesystem reference to files placed in the war similar to how this is?

Is it perhaps a url I grab on servlet initialization? I could obviously have a properties file that explicitly points to the installed directory but I would like to avoid additional configs.

like image 341
benstpierre Avatar asked May 06 '11 18:05

benstpierre


2 Answers

If you can guarantee that the WAR is expanded, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system which you can further use in the usual Java IO stuff.

String relativeWebPath = "/IMAGES/image1.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

However, if you can't guarantee that the WAR is expanded (i.e. all resources are still packaged inside WAR) and you're actually not interested on the absolute disk file system path and all you actually need is just an InputStream out of it, then use getServletContext().getResourceAsStream() instead.

String relativeWebPath = "/IMAGES/image1.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

See also:

  • getResourceAsStream() vs FileInputStream
like image 191
BalusC Avatar answered Nov 03 '22 00:11

BalusC


Use the getRealPath method of ServletContext.

Ex:

String path = getServletContext().getRealPath("WEB-INF/static/img/myfile.jpeg");
like image 36
Mike Thomsen Avatar answered Nov 02 '22 23:11

Mike Thomsen