How to get the URL of a resource in the classpath in WebSphere 6.1?

The code below works fine in Tomcat, but calling getResource (...) returns null in WebSphere 6.1. I tried using as Thread.currentThread (). GetClassLoader () and MyClass.class.getClassLoader () - both return null.

URL url = null; ClassLoader cl = MyClass.class.getClassLoader(); LOG.info("Using class 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 also tried it, 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 that? How to get resource url in classpath correctly?

+4
source share
2 answers

I would suggest that the difference is in how ClassLoader . Can you use the Class option instead? MyClass. class.getResource () ? We use Class.getResourceAsStream() in WebSphere 6.1 all the time.

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

Using the Class option, your relative path will look in the resources subdirectory in the MyClass package. But the ClassLoader option cannot be.

+4
source

In the servlet container, you should use ServletContext.getResource() and ServletContext.getResourceAsStream() instead of Class.getResource() and Class.getResourceAsStream() respectively. This is more likely to behave sequentially in different servlet containers.

Also, double-check that your relative path is correct in the context in which you use it. Try the absolute path and see if it works better.

+1
source

Source: https://habr.com/ru/post/1399091/


All Articles