Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to load a binary image file to do some processing inside my server-side Java code. I am currently placing my image in the package where my executing class exists and calling:

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

This works fine when I'm running Tomcat on my development box in an exploded war setup, but when I deploy to a server running Tomcat where it doesn't explode war files, the call to getResource returns null.

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

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

Again, this works on my development box, but not when I deploy it elsewhere.

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

Thanks!!

like image 902
11101101b Avatar asked Jan 06 '12 18:01

11101101b


People also ask

How do I access WAR files?

Assuming we already have our WAR file to hand, and would like to deploy it using the management dashboard, we can access the manager dashboard by visiting: http://localhost:8080/manager.

Where are WAR files stored?

The location for WAR files is the webapps directory within your Tomcat installation directory.

What is the content of WAR file?

Each WAR file contains servlets, JSPs, a deployment descriptor, and related resource files. Static HTML files and JSP are stored at the top level of the WAR directory. The top-level directory contains the WEB-INF subdirectory which contains tag library descriptor files in addition to the following: Server-side classes.


1 Answers

If you are building using Maven, you'll want to make sure the image actually gets placed into the archive.

Put resources in your src/main/resources directory. Then access them with:

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

or:

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

(Code samples from comment above, but put in the answer to be more visible)

like image 119
checketts Avatar answered Sep 24 '22 19:09

checketts