【问题标题】:How do I correctly get a URL for a resource on the classpath in WebSphere 6.1?如何在 WebSphere 6.1 中正确获取类路径中资源的 URL?
【发布时间】:2012-03-01 07:09:39
【问题描述】:

以下代码在 Tomcat 中运行良好,但在 WebSphere 6.1 中调用 getResource(...) 返回 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.");
    }

...我也试过这个,没有运气...

   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.");
    }

这是怎么回事?如何正确获取类路径上资源的 URL?

【问题讨论】:

    标签: java websphere classpath classloader


    【解决方案1】:

    我猜想区别在于ClassLoaders 的行为方式。您可以改用Class 变体吗?我的班级.class.getResource()?我们一直在 WebSphere 6.1 下使用Class.getResourceAsStream()

    或者尝试在资源路径前加上斜杠。

    使用Class 变体,您的相对路径将在MyClass 包下的resources 子目录中查找。但ClassLoader 变体可能不会。

    【讨论】:

    • 我已经尝试过类变体。没运气。但我有钱在解决问题的领先斜线上......现在重建测试......我们很快就会发现:)
    【解决方案2】:

    在 servlet 容器中,您应该分别使用 ServletContext.getResource()ServletContext.getResourceAsStream() 而不是 Class.getResource()Class.getResourceAsStream()。它更有可能在不同的 servlet 容器中表现一致。

    此外,请仔细检查您的相对路径在您使用它的上下文中是否正确。尝试使用绝对路径,看看是否效果更好。

    【讨论】:

    • "此方法与 java.lang.Class.getResource 的用途不同,后者基于类加载器查找资源。此方法不使用类加载器。" Class 方法在 WebSphere 中绝对有效。
    • @dbreaux:Class 方法可能对您“有效”,但如果您正在加载 Web 应用程序中的资源,建议使用 ServletContext 中的方法。这就是它们的设计目的。事实证明,前导斜线足以帮助容器找到资源并解决了 OP 的问题。但我仍然建议切换到 ServletContext 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2012-05-13
    • 2014-05-05
    • 2018-10-09
    相关资源
    最近更新 更多