我们的 war/WEB-INF 文件夹中资源的文件路径? [英] File path to resource in our war/WEB-INF folder?

查看:37
本文介绍了我们的 war/WEB-INF 文件夹中资源的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用引擎项目的 war/WEB-INF 文件夹中有一个文件.我在常见问题解答中读到,您可以在 servlet 上下文中从那里读取文件.我不知道如何形成资源的路径:

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

我将如何构建该资源的路径以与 File() 一起使用,就像上面看到的那样?

How would I construct my path to that resource to use with File(), just as it looks above?

谢谢

推荐答案

有几种方法可以做到这一点.只要扩展WAR文件(一组文件而不是一个.war文件),就可以使用这个API:

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");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

这将为您提供所需资源的完整系统路径.但是,如果 Servlet 容器从不扩展 WAR 文件(如 Tomcat),这将不起作用.可以使用 ServletContext 的 getResource 方法.

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");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

无论您使用什么 Servlet 容器以及应用程序安装在何处,后一种方法都适用.前一种方法只有在部署前解压缩 WAR 文件时才有效.

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.

getContext() 方法显然是您必须实现的.JSP 页面使其可用作 context 字段.在 servlet 中,您可以从 ServletConfig 获取它,它被传递到 servlet 的 init() 方法中.如果你在那个时候存储它,你可以在之后任何你想要的时候获取你的 ServletContext.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆