更新时间:2023-11-17 23:04:22
/ WEB-INF
文件夹是不是类路径的一部分。所以这里的任何答案都没有意义,建议 ClassLoader#getResourceAsStream()
将从不工作。它只有在属性文件放在 / WEB-INF / classes
中才有效,这确实是类路径的一部分(在像Eclipse这样的IDE中,只是放在Java源代码中)文件夹root应该足够了。
The /WEB-INF
folder is not part of the classpath. So any answer here which is thoughtless suggesting ClassLoader#getResourceAsStream()
will never work. It would only work if the properties file is placed in /WEB-INF/classes
which is indeed part of the classpath (in an IDE like Eclipse, just placing it in Java source folder root ought to be sufficient).
如果属性文件确实存在于你想保留它的位置,那么你应该把它作为web内容资源通过 ServletContext#getResourceAsStream()
代替。
Provided that the properties file is really there where you'd like to keep it, then you should be getting it as web content resource by ServletContext#getResourceAsStream()
instead.
假设你在 HttpServlet里面
,这应该做:
properties.load(getServletContext().getResourceAsStream("/WEB-INF/properties/sample.properties"));
( getServletContext()
继承自servlet超类,你不需要自己实现它;所以代码是原样的)
(the getServletContext()
is inherited from the servlet superclass, you don't need to implement it yourself; so the code is as-is)
但是如果类是本身不是 HttpServlet
,那么你真的需要将属性文件移动到类路径中。
But if the class is by itself not a HttpServlet
at all, then you'd really need to move the properties file into the classpath.