Resolving the root of a webapp from getResource

☆樱花仙子☆ 提交于 2019-12-03 20:36:51

Well, first of all, this.getClass().getResource should not work (though I didn't try). It's not a classpath, it's a ServletContext, so you need to use ServletContext.getResource.

Problem is, it is not necessary a file: it can be an entry in a WAR archive. So depending on what exactly you know, the answer may be different.

We use a Spring utility class which handles both files (via ServletContext.getResourcePaths if available) and WARs (via ServletContext.getResource). If you use Spring, that may be the best way. If you don't, you'll probably need to re-implement the solution.

Alternatively, you cal simply use ServletContext.getResourceAsStream—it doesn't care where exactly the resource is stored. So as long as you need its content and not the path, you should be fine.

No, it won't resolve. Class.getResource loads resources from the classpath, and the webapp's root directory is not itself on the classpath.

In order to get hold of that resource, you'll need to get hold of the ServletContext, on which you can then call ServletContext.getResource("/WEB-INF/reports/info.txt"). That should work.

You can obtain the ServletContext using Servlet.getServletConfig().getServletContext().

Alternatively, move your reports directory under the /WEB-INF/classes directory (which is on the classpath). You can then get your file using

getClass().getResource("reports/info.txt");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!