如何在JSP中访问WEB-INF中的文件? [英] How do I access file in WEB-INF in JSP?
问题描述
我正在使用Tomcat。我想将配置文件放在 WEB-INF
中,而不是默认的根类路径,即 WEB-INF / classes
。目前我将 config.xml
放在 WEB-INF
中,并使用以下相对寻址来找到它:
I am using Tomcat. I would like to put the config file in WEB-INF
instead of the default root class path which is WEB-INF/classes
. Currently I put the config.xml
in WEB-INF
and use the following relative addressing to locate it:
InputStream input = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("..//config.xml");
这是正确的方法吗?
或者我应该首先使用 getServletContext()。getRealPath(config.xml)
?但我不知道如何在 .java
中获取 getServletContext()
。 (我尝试新的HttpServlet
获取 getServletContext()
,但由于它是一个抽象类,不能instanced ...如何获得 getServletContext()
?)
Or should I use the getServletContext().getRealPath("config.xml")
first? But I don't know how to obtain the getServletContext()
in a .java
. (I tried to new HttpServlet
for obtaining getServletContext()
, but since it is an abstract class, can't be instanced... how can I get the getServletContext()
?)
推荐答案
方法 getRealPath()
不能保证有效,例如如果您的webapp没有从war文件扩展,那么文件系统上没有'真实路径'到war文件中的文件。
The method getRealPath()
is not guaranteed to work, e.g. if your webapp is not expanded from a war file there is no 'real path' on the filesystem to a file inside the war file.
因为你说你使用的是 ServletContextListener ,您可以从中获取ServletContext ServletContextEvent :
Since you say you are using a ServletContextListener, you can get the ServletContext out of the ServletContextEvent:
sce.getServletContext().getResourceAsStream("/WEB-INF/config.xml");
这篇关于如何在JSP中访问WEB-INF中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!