Programmatically reading static resources from my java webapp

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 through my / jsp / etc servlets, I can simple link to

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

and

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

I'm not writing a servlet that needs to get a link to these files for the file system (in order to display a composite .pdf file in this case). Does anyone have a suggestion on how to get a file system link to files hosted in a war like this?

Perhaps this is the url that I use to initialize the servlet? I could explicitly have a properties file that explicitly points to the installed directory, but I would like to avoid additional configurations.

+5
4

WAR, ServletContext#getRealPath() - , Java IO.

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

, WAR ( - WAR), , , , InputStream , getServletContext().getResourceAsStream().

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

. :

+12

getRealPath ServletContext.

:

String path = getServletContext().getRealPath("WEB-INF/static/img/myfile.jpeg");
+5

, .:

InputStream is =  YourServlet.class.getClassLoader().getResourceAsStream("IMAGES/img1.jpg");

getResoruce, . . , , , .

-2

, ,

Thread.currentThread().getContextClassLoader().getResource(<relative-path>/<filename>)

URL- , . URL- , URL- .

-3

All Articles