这是我的项目结构:
这是我部署在tomcat服务器之后,右键项目选择“Browse deployment location...”看到的结构:
可以看到,在tomcat服务器下,应用程序的根目录就是原来项目WebRoot下面的内容。想要获取a.properties、b.properties、c.properties这三个文件的内容,使用getRealPath(String path)方法:
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
test1();
test2();
test3();
}
private void test3() throws IOException, FileNotFoundException {
// 得到c.properties
String path = this.getServletContext().getRealPath("/WEB-INF/classes/com/test/getresources/c.properties");
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
private void test2() throws IOException, FileNotFoundException {
// 得到b.properties
String path = this.getServletContext().getRealPath("/WEB-INF/classes/b.properties");
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
private void test1() throws IOException, FileNotFoundException {
// 得到a.properties
String path = this.getServletContext().getRealPath("/WEB-INF/a.properties");
Properties prop = new Properties();
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("key"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器访问TestServlet,控制台输入三个文件的内容:
注意:getRealPath() 方法根据资源名称的到资源的绝对路径,但是该方法对于不同的app server会返回不同的结果,同时,该方法会受到 war 和 non-war 的影响,对于一个打包应用来说,是没有RealPath概念的。
因此,推荐使用getResourceAsStream(Strig path)的方法:
private void test4() throws IOException {
// 使用getResourceAsStream
Properties prop = new Properties();
prop.load(this.getServletContext().getResourceAsStream("/WEB-INF/a.properties"));
System.out.println(prop.getProperty("key"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
test1();
test2();
test3();
test4(); // 使用getResourceAsStream
}
运行结果如下: