【问题标题】:Where to place a directory of static files in Eclipse Dynamic Web Project在 Eclipse 动态 Web 项目中放置静态文件目录的位置
【发布时间】:2013-03-19 17:24:17
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 将abc.txt文件放在jsp文件所在的同一个文件夹中

标签: eclipse jsp static


【解决方案1】:

您不能直接从 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("/");,它返回您的Web应用程序的webapps目录的路径,然后您可以使用此路径访问资源。

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

这里是示例截图

Servlet 代码:

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
    }
}

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 2012-10-05
    • 2017-10-23
    • 2013-03-08
    • 1970-01-01
    • 2017-07-04
    • 2012-05-15
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多