我该如何在JSP中访问WEB-INF文件?

3

我正在使用Tomcat。我想把配置文件放在WEB-INF中,而不是默认的根类路径WEB-INF/classes。目前,我将config.xml放在WEB-INF中,并使用以下相对地址来定位它:

InputStream input = Thread.currentThread()
    .getContextClassLoader()
    .getResourceAsStream("..//config.xml");

这是正确的做法吗?
或者我应该先使用getServletContext().getRealPath("config.xml")?但我不知道如何在.java中获取getServletContext()。(我尝试使用new HttpServlet来获取getServletContext(),但由于它是一个抽象类,无法实例化...我该如何获取getServletContext()?)
2个回答

6

getRealPath()方法不能保证可用,例如如果您的Web应用程序没有从war文件中展开,则在war文件内部没有指向文件的'真实路径'。

由于您说您正在使用ServletContextListener,因此可以从ServletContextEvent中获取ServletContext:

sce.getServletContext().getResourceAsStream("/WEB-INF/config.xml");

2
你可以使用 getServletConfig() 方法返回一个 ServletConfig 的实例。
ServletContext sc=getServletConfig().getServletContext();

编辑:

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
  ServletContext sc=getServletContext();
  ...
}

1
谢谢你的回答。我尝试在 .java 文件中使用 getServletConfig(),但它报错说 "The method getServletConfig() is undefined for ..."。(目前我的 .java 类实现了 ServeletContextListener。)我还需要设置什么才能使用 getServletConfig() 吗?谢谢。 - Ken
1
它在ServletContextEvent.getServletContext()中。 - Chuk Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接