【问题标题】:Read properties file on glassfish 4读取 glassfish 4 上的属性文件
【发布时间】:2014-02-06 21:14:18
【问题描述】:

我需要在 glassfish 4 应用程序中读取属性文件。该文件需要位于应用程序中的某个位置(即不在文件系统中的某个随机位置)。

如果重要的话,我是用eclipse开发,项目用maven构建,神器就是一场战争。

在我看来,要完成这项工作,我需要知道三件事。

1) 原始文件需要放在哪里?

2) 文件需要在哪里结束?

3) 如何阅读?

到目前为止,我创建了文件:

src/main/resources/version.properties

结束
WEB-INF/classes/version.properties

我不知道那是不是正确的位置。

基于类似的问题,我定义了一个ServletContextListener:

public class ServletContextClass implements ServletContextListener {
...
   @Override
   public void contextInitialized(ServletContextEvent arg0) {
       ServletContext ctx = arg0.getServletContext();
       InputStream istream = ctx.getResourceAsStream("version.properties"); 

       // at this point, istream is null

       Properties p = new Properties();
       p.load(istream);
   }
}

我不确定我的文件是不是放错了地方,是不是我读错了,或者两者兼而有之。

更新:以下“作品”:

   @Override
   public void contextInitialized(ServletContextEvent arg0) {
       ResourceBundle bundle =  ResourceBundle.getBundle("version");
       if (bundle == null) { 
          logger.info("bundle is null");
       } else {
          logger.info("bundle is not null");
          logger.info("version: " + bundle.getString("myversion"));
       }
   }

但是,我认为这不是正确的解决方案。捆绑包用于支持语言环境,不属于该类别。

更新 2:我更正了文件结束的位置。

【问题讨论】:

    标签: java glassfish war


    【解决方案1】:

    1) 将version.properties文件放入

    src/main/resources/version.properties
    

    似乎是正确的。

    2) 在目标战争中,文件实际上确实以

    结尾
    WEB-INF/classes/version.properties
    

    3) 读取文件:我已经定义了一个 ServletContextListener。如果不需要,则需要定义一个并在 web.xml 中进行配置。这是我的 ServletContextListener 的一部分:

       package com.mycompany.service;
    
       public class ServletContextClass implements ServletContextListener {
            @Override
            public void contextInitialized(ServletContextEvent arg0) {
               ServletContext ctx=arg0.getServletContext();
    
               try {
                  Properties p = new Properties();
                  InputStream istream = ctx.getResourceAsStream("/WEB-INF/classes/version.properties");
                  p.load(istream);
                  Properties sysProps = System.getProperties();
                  sysProps.putAll(p);
              } catch (IOException e) {
                  logger.error("Error reading " + "version.properties");
              }
           }
        }
    

    就是用这段web.xml配置的:

    <listener>
        <listener-class>com.mycompany.service.ServletContextClass</listener-class>
    </listener>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2018-09-17
      • 2016-10-20
      • 1970-01-01
      相关资源
      最近更新 更多