1

I have a JAVA EE app. with this structure:

/iberiaApp
/iberiaApp/configFiles/hotel
/iberiaApp/config.jsp
/iberiaApp/WEB-INF/classes

inside config.jsp I have this piece of code:

 <%=FileReader.readFiles("configFiles/hotel")%>;

and

public static List<String> readFiles (String folder) throws URISyntaxException {

    ClassLoader classLoader = FileReader.class.getClassLoader();

    URI uri = classLoader.getResource(folder).toURI();

But I got a nullpointer getting the URI (classLoader.getResource(folder) is returning null)

en Lopes
  • 1,863
  • 11
  • 48
  • 90
  • First, try to call methods separately to figure out what method returns null. Looking that line probably `classLoader.getResource(folder)` is returning null. The class loader is loooking for resources from `/iberiaApp/WEB-INF/classes`. – Ele Dec 08 '17 at 14:10

2 Answers2

-2

The web app root directory itself is not on the runtime classpath, so you can’t load a resource relative to the web app root via a class loader. Put the configuration files under src/main/resources, so at runtime they will be under WEB-INF/classes, and accessible via class loading.

Also you don’t want keep your config files under the web app root anyway, because then they are accessible to the web app users directly.

jingx
  • 3,698
  • 3
  • 24
  • 40
-2

Look a these notes from: https://stackoverflow.com/a/3160706/1715121

Several notes:

  1. You should prefer the ClassLoader as returned by [Thread#getContextClassLoader()][1].

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    

    This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

  2. The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

    classLoader.getResource("/configFiles/hotel");
    
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Both points are incorrect. The only ClassLoader he should use is the one corresponding to the class doing the loading. And ClassLoader.getResource *always* requires a string which does not have a leading slash. – VGR Dec 08 '17 at 14:48