【问题标题】:properties file call in Java servletJava servlet 中的属性文件调用
【发布时间】:2014-09-12 04:17:00
【问题描述】:

我从 Java 中的属性文件开始,我正在关注 this tuto

它在我的应用程序中运行良好,除非我需要 servlet 中的属性。 如果从 servlet 或从“普通”类执行相同的函数调用,则不会给出相同的结果。 路径变得错误,我不知道为什么。 也许 servlet 的路径来自服务器。

input = new FileInputStream(filename);
prop.load(input);

当我使用 servlet 执行这些行时,filename 的路径在哪里?

【问题讨论】:

    标签: java servlets properties


    【解决方案1】:

    当我使用 servlet 执行这些行时,filename 的路径在哪里?

    这可能会对您有所帮助:

    File file = new File(filename);
    System.out.println(file.getAbsolutePath());
    

    如果属性文件确实在您想要保留的位置,那么您应该通过ServletContext#getResourceAsStream() 将其作为网络内容资源获取。

    示例代码:

    properties.load(getServletContext()
                     .getResourceAsStream("/WEB-INF/properties/sample.properties"));
    

    Read more...


    交替

    注册ServletContextListener以在服务器启动时加载初始化参数,您可以随时更改配置文件位置,而无需更改任何java文件。

    加载属性并使其对其他类静态可见。

    示例代码:

    public class AppServletContextListener implements ServletContextListener {
        private static Properties properties;
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            String cfgfile = servletContextEvent.getServletContext().getInitParameter("config_file");
            properties.load(new FileInputStream(cfgfile));
        }
        
        public static Properties getProperties(){
            return properties;
        }
    }
    

    web.xml:

    <listener>
        <listener-class>com.x.y.z.AppServletContextListener</listener-class>
    </listener>
    
    <context-param>
          <param-name>config_file</param-name>
          <param-value>config_file_location</param-value>
    </context-param>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2014-02-25
      • 2021-03-30
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多