【问题标题】:Find the path of file in same directory during RUNTIME在运行时查找同一目录中的文件路径
【发布时间】:2015-06-22 11:58:31
【问题描述】:

我有一个struts2 和hibernate 应用程序。我打算做的是,如果数据库配置无效,我从用户那里收到它并使用更新的设置修改 hibernate.hbm.xml。我能够检查和接收用户的设置,唯一的问题是 domparser 找不到我的 hibernate.cfg.xml。

String filepath = "hibernate.cfg.xml";
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);

当以普通用户身份部署应用程序时,我得到了这个

/home/uzumaki/hibernate.cfg.xml (No such file or directory)

当我以 root 身份运行时,

/hibernate.cfg.xml (No such file or directory)

使用 File("").getAbsolutePath()) 并与 hibernate.cfg.xml 连接也会给我​​同样的错误。 该文件当然不存在,它与我的 java 代码/类在同一个文件夹中,并且随处可见(示例 war 文件)

【问题讨论】:

  • 使用this.getResource("hibernate.cfg.xml")。在我看来,允许在运行时更改休眠文件看起来并不安全。
  • @Priyesh、wordpress、phpbb 等,无论其平台如何,都自行编写数据表配置。我只想做同样的事情,删除硬编码。

标签: java hibernate jsp servlets domparser


【解决方案1】:

经过大量搜索,我终于找到了一种在运行时获取应用程序真实路径的方法。我发布这个以防有人需要。

HttpServletRequest servletRequest = ServletActionContext.getRequest();
String app_path;
app_path = servletRequest.getSession().getServletContext().getRealPath("/");

现在(以我为例)

String filepath =  app_path  + "WEB-INF/classes/hibernate.cfg.xml";

【讨论】:

  • 这种方法存在两个主要的概念问题。 1) 当服务器配置为在内存中而不是在磁盘文件系统中扩展 WAR 时,getRealPath() 将返回 null。 2) 部署后的任何更改都会在重新部署 WAR 时丢失,有时甚至在服务器重新启动时也会丢失,原因很简单,这些更改不包含在原始 WAR 中。你可能想修改你的方法。另见 a.o. stackoverflow.com/questions/2161054/…
  • @BalusC 1)当我复制战争或从管理器部署它时,文件会自行提取 - 即使重新启动,这些文件也会持续存在。 2)是的,如果重新部署战争,更改将会丢失,但重新部署主要是为了重新开始..
猜你喜欢
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2010-11-21
相关资源
最近更新 更多