我正在寻找类似 request.getServletContext().getRealPath()
的东西在自定义类中使用(Hibernate 中的拦截器,它无法访问 request
对象)。
File file = new File("/photo/test.txt");
file.delete();
...上面的代码会失败,因为file
的路径现在是Tomcat的/lib
目录。
但我需要从项目开始计数,而不是 Tomcat。
有什么想法吗?
最佳答案
恕我直言,对您来说最简单的方法是在 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");
关于Java (JSP) 项目的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24559723/