How can I read the resource file in an unexploded war file deployed to Tomcat?

I am trying to upload a binary image file to do some processing inside my server side Java code. Currently, I put my image in a package where my executable class exists and the caller:

Image img = Image.getInstance(this.getClass().getResource("logo.png"));

This works fine when I launch Tomcat in my exploded window in exploded war mode, but when I deploy a server running Tomcat where it does not explode war files, the getResource call returns null.

I also tried moving the image to my root context and accessing it like this:

Image img = Image.getInstance(this.getClass().getResource("/../../logo.png"));

Again, this works in my development window, but not when I deploy it elsewhere.

Is there a better way to access this file? What am I doing wrong?

Thank!!

+5
source share
2 answers

If you are building using Maven, you need to make sure that the image really gets into the archive.

Put the resources in the directory src/main/resources. Then follow these steps:

this.getClass().getResource("/logo.png"); 

or:

Thread.currentThread().getContextClassLoader().getResource("logo.png"); 

(Code samples from the comment above, but the answer to it is more visible)

+5
source

You can put your images at the root of your class path and try the following:

Thread.currentThread().getContextClassLoader()
               .getResource("logo.png");
+1
source

All Articles