Search code examples
javashelltomcatclassloaderwar

How can I locate a non-Java resource in a WAR at runtime?


I need to run a shell script at runtime from a WAR that I run on Tomcat.

Thus, I've placed my script theScript.sh in my src/main/resources directory (because, yes, I use Maven). This directory is in the classpath, I've checked it.

In the code, I want to copy my script in a temp directory. So I've tried to get it via my ClassLoader:

URL myURL = ClassLoader.getSystemResource("theScript.sh");
if (myURL == null) {
    LOG.error("Couldn't find the resource");
}

And guess what? Yes, the "Couldn't find the resource" keeps appearing all over the place in my logs.

Any idea what I'm doing wrong here?

My environment is the traditional Eclipse/Tomcat thing.


Solution

  • You don't want to use the System cloassloader - that would typically only find resources that are part of Tomcat or the JRE.

    You want to load the resource from the classloader that was used to load your WAR file. There's a couple of ways to do that, but the official way would be to get access to the ServletContext (javadoc) and call either getResource or getClassLoader().getResource on that.

    If you don't have the ServletContext available, then you can "cheat" by using the classloader for a class that you know came from your WAR file. Something like

    this.getClass().getClassLoader().getResource("xyz");
    

    where this is your class that's been deployed inside your WAR file.