简体   繁体   中英

How do I correctly get a URL for a resource on the classpath in WebSphere 6.1?

The code below works beautifully in Tomcat, but the call to getResource(...) returns null in WebSphere 6.1. I've tried using both Thread.currentThread().getClassLoader() and MyClass.class.getClassLoader() - both return null.

    URL url = null;
    ClassLoader cl = MyClass.class.getClassLoader();
    LOG.info("Using class's classloader.");

    url = cl.getResource("resources/AConfigFile.xml");

    if(url == null) {
        throw new RuntimeException("The ClassLoader returned null for the URL of the " +
                "the XML Document.  This is definitely not right.");
    }

...and I have also tried this, with no luck...

   URL url = null;

    url = MyClass.class.getResource("resources/AConfigFile.xml");

    if(url == null) {
        throw new RuntimeException("The ClassLoader returned null for the URL of the " +
                "the XML Document.  This is definitely not right.");
    }

What's up with this? How do I properly get a URL for a resource on the classpath?

I'd guess the difference is the way the ClassLoader s behave. Can you use the Class variant instead? MyClass. class.getResource() ? We use Class.getResourceAsStream() under WebSphere 6.1 all the time.

Or perhaps try prefacing your resource path with a leading slash.

Using the Class variant, your relative path will look in the resources subdirectory under the package of MyClass . But the ClassLoader variant might not.

Within a servlet container, you should use ServletContext.getResource() and ServletContext.getResourceAsStream() instead of Class.getResource() and Class.getResourceAsStream() respectively. It's more likely to behave consistently across different servlet containers.

Also, double check that your relative path is correct in the context you're using it in. Try an absolute path and see if that works any better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM