首页 文章

为什么我可以在Java应用程序中加载属性,而不是Java servlet? [重复]

提问于
浏览
0

这个问题在这里已有答案:

(在搜索StackExchange之后)我无法弄清楚为什么我可以使用 main() 方法从简单的 Java class 加载我的属性文件,但不能从 Java servlet 加载 . 例外是 java.io.FileNotFoundException: resources\dbprops.properties (The system cannot find the path specified)
有人可以帮我把属性文件加载到我的servlet中吗?
(假设这些类中还有其他方法和导入)

项目布局:

project\
    src\
        joerle\
            servlet\
                MyServlet.java
            jdbc\
                JdbcTest.java
    resources\
        dbprops.properties

简单的java类 joerle.jdbc.JdbcTest (加载属性):

public class JdbcTest {
    private final String dbPropPath = "resources" + File.separator + "dbprops.properties";
    private Properties props;

    public JdbcTest() {
        try {
            props = new Properties();
            props.load(new FileInputStream(dbPropPath));
            //do stuff
        } catch (FileNotFoundException e) {
            System.err.println("properties file not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("properties file cannot be opened");
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new JdbcTest();
    }
}

简单的java servlet类 joerle.servlet.MyServlet (无法加载属性):

public class MyServlet extends HttpServlet {
    private final String dbPropPath = "resources" + File.separator + "dbprops.properties";
    private Properties props;

    public void init(ServletConfig config) throws ServletException {
        try {
            props = new Properties();
            props.load(new FileInputStream(dbPropPath));
            //do stuff
        } catch (FileNotFoundException e) {
            System.err.println("properties file not found");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("properties file cannot be opened");
            e.printStackTrace();
        }
    }
}

我已经尝试过了:

提前致谢!

1 回答

  • 0

    这是我使用的解决方案,它在servlet上下文中成功运行:

    • 已将属性文件移至 projectRoot/WebContent/WEB-INF/classes/resources/dbprops.properties

    • 并用它调用它:
      InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/dbprop.properties");

    如果使用此解决方案,请注意斜杠的位置 . 这对我的故障排除来说是一个很好的资源:Where to place and how to read configuration resource files in servlet based application?

相关问题