简体   繁体   English

Java(JSP)项目的相对路径

[英]Java (JSP) relative path to the project

I looking for something like of request.getServletContext().getRealPath() to use inside custom class (interceptor in Hibernate, which hasn't access to request object). 我在寻找类似于request.getServletContext().getRealPath()东西在自定义类中使用(Hibernate中的拦截器,它无法访问request对象)。

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

... above code will fail, because the path of file is /lib directory of Tomcat now. ...上面的代码将失败,因为file的路径现在是Tomcat的/lib目录。

But i need to start count from the project, not Tomcat. 但我需要从项目开始计数,而不是Tomcat。

Any ideas? 有任何想法吗?

getRealPath will return the path from the root and beyond. getRealPath将返回root和更远的路径。

You should use the context path, instead. 您应该使用上下文路径。

Take a look at this thread 看看这个帖子

try to use 试着用

request.getServletContext().getContextPath();

IMHO the simplest way for you is to get the root of your application in a ServletContextListener declared in web.xml or via a WebListener annotation and to store it in a static variable. 恕我直言,最简单的方法是在WebListener声明的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;
    }
}

That way you will have access to the root path of your application from anywhere as RootPathHolder.getRootPath() and in your interceptor you will only need to do a path concatenation : 这样,您可以从RootPathHolder.getRootPath()任何位置访问应用程序的根路径,并且在您的拦截器中,您只需要进行路径连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM