Java(JSP)项目的相对路径

时间:2014-07-03 17:15:21

标签: java hibernate jsp tomcat path

我在自定义类中使用request.getServletContext().getRealPath()之类的东西(Hibernate中的拦截器,它无法访问request对象)。

File file = new File("/photo/test.txt");
file.delete();

...上面的代码将失败,因为file的路径现在是Tomcat的/lib目录。

但我需要从项目开始计算,而不是Tomcat。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

getRealPath将返回root和更远的路径。

您应该使用上下文路径。

查看this thread

尝试使用

request.getServletContext().getContextPath();

答案 1 :(得分:1)

恕我直言,最简单的方法是将您的应用程序的根目录放在web.xml中声明的ServletContextListener或通过WebListener注释中,并将其存储在静态变量中。

public class RootPathHolder implements ServletContextListener {
    static String rootPath;

    public void contextInitialized(ServletContextEvent sce) {
        RootServletListener.rootPath = sce.getServletContext().getRealPath("/");
    }

    public void contextDestroyed(ServletContextEvent sce) {
    }

    public static String getRootPath() {
        return rootPath;
    }
}

通过这种方式,您可以从RootPathHolder.getRootPath()的任何位置访问应用程序的根路径,在拦截器中,您只需要进行路径连接:

Path realPath = Paths.get(RootPathHolder.getRootPath(), "photo/test.txt");