我在访问WebContent文件夹中的文件时遇到问题(在这种情况下,我需要访问WEB-INF文件夹)

这是我尝试访问WEB-INF文件夹的地方。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String dbPath = "/WEB-INF/musicDb.db";
    String xmlPath = "/WEB-INF/musicDb.xml";
    ServletContext context = null;
    context = getServletContext();
    String test = context.getRealPath(xmlPath);

    File f = new File(test);
    if (f.exists()) {

    }
}


我已经在WEB-INF文件夹中准备好musicDb.xml,但是通过调试,我总是得到此路径

{my local project path}/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/9321A1/WEB-INF/musicDb.xml


java - 无法从Servlet访问WEB-INF文件夹中的文件-LMLPHP

我怀疑这与WebContent文件夹未包含在构建过​​程中有关。这可能是错误的。

到目前为止,我发现的几乎所有教程/建议/文章都将我介绍给使用这种方法


  getServletContext()。getRealPath()


在我的情况下似乎不起作用

任何帮助,将不胜感激。

最佳答案

我建议您将文件移动到/ WEB-INF / classes或将其打包在jar中,然后将该jar放在WEB-INF / lib中。使用任何一种getResourceAsSteam方法将文件作为资源加载

参见此处:Best practices to store and access resource files in java web application和正确的答案:Reading Web Application Resources

09-10 10:00
查看更多