我们的war / WEB-INF文件夹中的资源文件路径? [英] File path to resource in our war/WEB-INF folder?
问题描述
我的应用程序引擎项目的war / WEB-INF文件夹中有一个文件。我在FAQ中读到,你可以从servlet上下文中读取文件。我不知道如何形成资源的路径:
/ war / WEB-INF / test / foo。 txt
我如何构建我的路径来使用File(),就像它看起来一样以上?
谢谢
。只要WAR文件被扩展(一组文件而不是一个.war文件),您就可以使用此API:
ServletContext context = getContext();
String fullPath = context.getRealPath(/ WEB-INF / test / foo.txt);
这将为您提供正在寻找的资源的完整系统路径。但是,如果Servlet容器永远不扩展WAR文件(如Tomcat),那将无法工作。使用ServletContext的 getResource
方法。
ServletContext context =的getContext();
URL resourceUrl = context.getResource(/ WEB-INF / test / foo.txt);
或者如果您只是想要输入流:
InputStream resourceContent = context.getResourceAsStream(/ WEB-INF / test / foo.txt);
无论您使用哪种Servlet容器以及应用程序的安装位置,后一种方法都可以使用。前一种方法只有在WAR文件在部署前解压缩才有效。
编辑:
getContext()方法明显你必须实施的东西。 JSP页面使它可用作上下文
字段。在一个servlet中,你可以从你的 ServletConfig
中获得它,它传递给servlet的 init()
方法。如果你在那个时候存储它,你可以在任何时候随时获得你的ServletContext。
I've got a file in my war/WEB-INF folder of my app engine project. I read in the FAQs that you can read a file from there in a servlet context. I don't know how to form the path to the resource though:
/war/WEB-INF/test/foo.txt
How would I construct my path to that resource to use with File(), just as it looks above?
Thanks
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
这篇关于我们的war / WEB-INF文件夹中的资源文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!