【问题标题】:Loading resource bundle outside WEB-INF/classes folder在 WEB-INF/classes 文件夹外加载资源包
【发布时间】:2012-11-18 08:40:51
【问题描述】:

由于某种原因,messages.properties 文件位于 WEB-INF 文件夹中的某个位置,但在 WEB-INF/classes 文件夹之外。具体来说,文件的路径是/WEB-INF/messages/messages.properties。如何使用ResourceBundle.getBundle( ? )方法加载这个资源包?

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/1172424/…
  • 因为只有类文件夹在类路径中,我看到的唯一可能的方法是以某种方式覆盖 Tomcat 类加载器。简单的方法是将消息文件夹放在类目录中。

标签: java resourcebundle


【解决方案1】:

我只是组合了一个 ResourceBundle.Control 扩展来处理这种确切的情况:

https://gist.github.com/Tzrlk/82d74c074e63955a8a35

用法:

ServletContext servletContext = //! get access to servlet context instance
Locale locale = //! get access to locale instance

try {
    ResourceBundle.Control control = new ServletContextBundleControl(servletContext);
    ResourceBundle bundle = ResourceBundle.getBundle("/WEB-INF/messages/messages", locale, control);
} catch (MissingResourceException error) {
    // handle exception 
}

【讨论】:

    【解决方案2】:

    您可以使用 Servlet 上下文获取路径,如下所示;

    getServletContext().getResource("/messages/messages.properties).getPath();
    

    然后使用 URLClassLoader() 创建一个类加载器并将其传递给 getBundle() 方法。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 2011-06-11
      相关资源
      最近更新 更多