简体   繁体   English

ServletContext.getResource从lib中获取资源

[英]ServletContext.getResource to get resource from within lib

I have a jar-file test.jar that is placed within WEB-INF/lib and contains a single file in its root: 我有一个jar文件test.jar放在WEB-INF / lib中,并且在其根目录中包含一个文件:

/
|- 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: 但是,尽管getResource的文档指出还搜索了WEB-INF / lib中的jar文件,但结果始终为null:

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResource%28java.lang.String%29 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? 我是否缺少某些东西,或者为什么我无法获得资源?

You already provided the link to the javadoc, quoting the relevant part: 您已经提供了指向Javadoc的链接,并引用了相关部分:

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. 该路径必须以/开头,并且被解释为相对于当前上下文根目录,或相对于 Web应用程序/WEB-INF/lib目录中JAR文件的/META-INF/resources目录。

So it is interpreted as relative to the /META-INF/resources folder in a jar file. 因此,它被解释为相对于jar文件中的/META-INF/resources文件夹。

However you indicated with a tag that you are using Tomcat. 但是,您使用标签指示正在使用Tomcat。 Tomcat implementation of the ServletContext.getResource() is somewhat different. Tomcat的ServletContext.getResource()实现有所不同。 It doesn't even mention the resource is searched in jar files. 甚至没有提到在jar文件中搜索资源。

Suggestion: don't put your resources in jar files if you want to access them with ServletContext.getResource() . 建议:如果要使用ServletContext.getResource()访问资源,请不要将其放在jar文件中。 If you do need to put them into jar files, then instead use the Class.getResource() method, eg put an optionally empty class into the jar file, and use that to access/load the resource, for example: 如果确实需要将它们放入jar文件,请改用Class.getResource()方法,例如,将可能为空的类放入jar文件,然后使用该类来访问/加载资源,例如:

Jar content: 罐内物品:

/
|- SomeClass.class
|- test.jsp

Java code to access test.jsp : Java代码访问test.jsp

SomeClass.class.getResource("/test.jsp"); // or it can even be "test.jsp"

You can use your thread's class loader to get your file as an InputStream like this: 您可以使用线程的类加载器将文件作为InputStream进行获取,如下所示:

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. getResourceAsStream()方法适用于类路径中的任何文件,无论是在目录中还是在JAR内部。

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

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