3

我使用 Eclipse 创建了一个动态 Web 项目。我有一些 Java 程序放在“Java Resources/src”文件夹中。这些程序使用Lucene我放在“ WebContent/WEB-INF/lib”文件夹中的库。Java 程序需要访问一些文本文件和一个包含由Lucene. 我将这些静态文件放在WebContenteclipse 下,以便它们出现在导出的 WAR 文件中。

我通过在 Java 程序中直接引用它们来访问这些静态文件。

BufferedReader br = new BufferedReader(new FileReader("abc.txt"));

//abc.txt 位于 Eclipse 项目的 WebContent 文件夹中。

在 JSP 页面中,我正在调用 java 程序(其中包含上述行),但它显示了一个FileNotFoundException. 请帮助我解决这个问题。

4

1 回答 1

3

您不能直接从 Java 访问 webapp 中可用的资源。

随着文件从编译时/src/YourClass.java消失。/WEB-INF/classes/因此,当您尝试访问BufferedReader br = new BufferedReader(new FileReader("abc.txt"));.

它根据您给定的示例在 /WEB-INF/classes/abc.txt 中搜索“abc.txt”。

使用servletContext.getRealPath("/");which 返回您的 Web 应用程序webapps目录的路径,然后您可以使用此路径访问资源。

注意:返回的路径servletContext.getRealPath("/");还取决于您如何部署 Web 应用程序。默认情况下,eclipse 使用自己的内部机制来部署 Web 应用程序。

这是关于它应该如何的示例屏幕截图Tomcat-Web 应用程序部署架构

小服务程序代码:

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StaticTestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ServletContext servletContext;
    private String rootPath;

    public StaticTestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        super.init(config);
        servletContext = config.getServletContext();
        rootPath = servletContext.getRealPath("/");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("In Get and my path: " + rootPath + "documents"); // documents is the direcotry name for static files
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        System.out.println("In Post and my path: " + rootPath + "documents"); // documents is the direcotry name for static files
    }
}
于 2013-03-20T06:36:57.853 回答