Does ServletContext.getRealPath() work with web fragments?

孤者浪人 提交于 2019-12-12 05:33:35

问题


I use web fragments (servlet 3 spec) and thus can load e.g. META-INF/resources/access.xml file which is in a library in /WEB-INF/lib/ of my WAR via ServletContext.getResourceAsStream("access.xml").

Doing the same with ServletContext.getRealPath("access.xml") doesn't work (=> null).

The spec states:

The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds. Resources inside the META-INF/resources directory of JAR file must be considered only if the container has unpacked them from their containing JAR file when a call to getRealPath() is made, and in this case MUST return the unpacked location.

My container (Tomcat) didn't unpack the jars, this seems to be the problem? How can Tomcat unpack the jars. Should I unpack the jars when packaging the WAR?


回答1:


So it depends on what you are trying to do. If you are trying to get the location of the file in the included library dependency, then I am not sure. If you are wanting to read the contents of the access.xml file then you can use

new InputStreamReader(context.getResourcesAsStream("access.xml")); 

and then work with the InputStreamReader to get the file's contents.




回答2:


Yes, getResourcesAsStream() always works. But getRealPath() doesn't.

Answer: Don't try to use getRealPath() together with web fragments.



来源:https://stackoverflow.com/questions/21094708/does-servletcontext-getrealpath-work-with-web-fragments

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