简体   繁体   English

如何在WebSphere 6.1中的类路径上正确获取资源的URL?

[英]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. 下面的代码在Tomcat中运行得很漂亮,但是对getResource(...)的调用在WebSphere 6.1中返​​回null。 I've tried using both Thread.currentThread().getClassLoader() and MyClass.class.getClassLoader() - both return null. 我尝试过使用Thread.currentThread()。getClassLoader()和MyClass.class.getClassLoader() - 都返回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? 如何正确获取类路径上的资源的URL?

I'd guess the difference is the way the ClassLoader s behave. 我猜不同之处在于ClassLoader的行为方式。 Can you use the Class variant instead? 您可以使用Class变体吗? MyClass. 我的课。 class.getResource() ? class.getResource() We use Class.getResourceAsStream() under WebSphere 6.1 all the time. 我们一直在WebSphere 6.1下使用Class.getResourceAsStream()

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 . 使用Class变量,您的相对路径将在MyClass包下的resources子目录中查找。 But the ClassLoader variant might not. ClassLoader变体可能不会。

Within a servlet container, you should use ServletContext.getResource() and ServletContext.getResourceAsStream() instead of Class.getResource() and Class.getResourceAsStream() respectively. 在servlet容器中,您应该分别使用ServletContext.getResource()ServletContext.getResourceAsStream()而不是Class.getResource()Class.getResourceAsStream() It's more likely to behave consistently across different servlet containers. 它更可能在不同的servlet容器中表现一致。

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. 此外,仔细检查您的相对路径在您使用它的上下文中是否正确。尝试一个绝对路径,看看它是否更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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