在Servlet/JSP中加载属性文件

bit*_*fer 6 java jsp servlets properties

我已经创建了一个jar来自我的Java project想要使用相同的jar JSP Servlet Project.我正在尝试加载一个属性文件,让我说我JSP Servlet Project保留的sample.properties WEB/properties/sample.properties应该被一个类中的类读取.我jar在一个jar 类中使用以下代码来访问它.

Properties prop=new Properties();
prop.load(/WEB-INF/properties/sample.properties);
Run Code Online (Sandbox Code Playgroud)

但每次我都会fileNotFound exception.
请建议我的解决方案.

这是结构

WEB-INF
      |
       lib
          |
           myproject.jar
                       |
                        myclass (This class needs to read sample.properties)
      |
       properties
                 |sample.properties
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 21

/WEB-INF文件夹不是类路径的一部分.因此,任何无法思考的答案都ClassLoader#getResourceAsStream()永远不会奏效.它只有在属性文件放置在/WEB-INF/classes类路径中时才会起作用(在像Eclipse这样的IDE中,只需将它放在Java源文件夹的根目录就足够了).

如果属性文件确实存在于您希望保留的位置,那么您应该将其作为Web内容资源获取ServletContext#getResourceAsStream().

假设你在里面HttpServlet,这应该做:

properties.load(getServletContext().getResourceAsStream("/WEB-INF/properties/sample.properties"));
Run Code Online (Sandbox Code Playgroud)

(getServletContext()继承自servlet超类,你不需要自己实现它;所以代码是原样的)

但是如果类本身不是一个HttpServlet,那么你真的需要将属性文件移动到类路径中.

也可以看看:


het*_*log 6

尝试将sample.properties放在src文件夹下,然后

Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("myprop.properties"));
Run Code Online (Sandbox Code Playgroud)