【问题标题】:Read Properties file in WEB-INF folder java using init使用init读取WEB-INF文件夹java中的属性文件
【发布时间】:2013-09-24 12:07:46
【问题描述】:

我正在尝试读取 WEB-INF 中的属性文件,但我得到的只是空值。我对 Java Web 开发完全陌生。

我的初始化方法:

 @Override
    public void init() throws ServletException {
        try {
            String path = "";
            path = "/WEB-INF/" + getServletContext().getInitParameter("monpesapropertiesfile");
            String realPath;
            realPath = getServletContext().getRealPath(path);
            if(realPath != null){
                 InputStream fis = new FileInputStream(realPath);
                 prop.load(fis);
            }
        } catch (Exception asd) {
            System.out.println(asd.getMessage());
        }
    }
    public String getDatabaseUrl() {
        String url = prop.getProperty("database.url");
        return url;
    }

我的 Web.xml:

<context-param>
        <param-name>monpesapropertiesfile</param-name>
        <param-value>monpesaproperties.properties</param-value>
    </context-param>
    <servlet>
        <servlet-name>ReadProperty</servlet-name>
        <servlet-class>com.monpesa.properties.ReadProperty</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

我知道我一定遗漏了一些东西,因为 String getDataBaseUrl 返回 null。请帮忙。

【问题讨论】:

    标签: java servlets properties


    【解决方案1】:

    我会的

    1) 将属性放入WEB-INF/classes 并使用getClass().getResourceAsStream() 加载。

    2) 将完整的文件路径放入 web.xml(并将文件放在 Web 应用程序之外的用户可编辑的配置区域中)

    【讨论】:

      【解决方案2】:

      看看这个:

      http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/javax/servlet/ServletContext.html#getResource(java.lang.String)

      <context-param>
          <param-name>monpesapropertiesfile</param-name>
          <param-value>/WEB-INF/monpesaproperties.properties</param-value>
      </context-param>
      
      public void init() throws ServletException {
          try {
              String path = getServletContext().getInitParameter("monpesapropertiesfile");
              final InputStream is = getServletContext().getResourceAsStream(path);
              try {
                  prop.load(is);
              } finally {
                  is.close();
              }
          } catch (Exception asd) {
              System.out.println(asd.getMessage());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 2011-01-09
        • 2012-11-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        相关资源
        最近更新 更多