1

I have a jar-file test.jar that is placed within WEB-INF/lib and contains a single file in its root:

/ |- test.jsp 

Now i would like to access this file from somewhere in my code:

this.getServletContext().getResource("/test.jsp"); 

But the result is always null although the documentation of getResource states that the jar-files within WEB-INF/lib are also searched:

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResource%28java.lang.String%29

Am i missing something or why can't i get the resource?

2 Answers 2

1

You already provided the link to the javadoc, quoting the relevant part:

The path must begin with a / and is interpreted as relative to the current context root, or relative to the /META-INF/resources directory of a JAR file inside the web application's /WEB-INF/lib directory.

So it is interpreted as relative to the /META-INF/resources folder in a jar file.

However you indicated with a tag that you are using Tomcat. Tomcat implementation of the ServletContext.getResource() is somewhat different. It doesn't even mention the resource is searched in jar files.

Suggestion: don't put your resources in jar files if you want to access them with ServletContext.getResource(). If you do need to put them into jar files, then instead use the Class.getResource() method, e.g. put an optionally empty class into the jar file, and use that to access/load the resource, for example:

Jar content:

/ |- SomeClass.class |- test.jsp 

Java code to access test.jsp:

SomeClass.class.getResource("/test.jsp"); // or it can even be "test.jsp" 
Sign up to request clarification or add additional context in comments.

3 Comments

Ouch... thanks for pointing me the that. But i changed the directory to /META-INF/resources/test.jsp and still get only null from getResource.
Edited my answer, Tomcat seems to be different.
I already noticed Tomcat not to mention the jar-scanning in their docs but i also tried Resin 4 and it doesn't work there either. I tried the dummy-class and it works. But i can't use that as i don't know which jar-file the resource is in (in the real case).
0

You can use your thread's class loader to get your file as an InputStream like this:

Thread.currentThread().getContextClassLoader().getResourceAsStream("test.jsp"); 

The method getResourceAsStream() works for any file in the classpath, whether it's in a directory or inside a JAR.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.