关于Servlet获取资源文件的路径问题

以eclipse中的java web项目为例,properties文件作为资源文件

有如下结构的项目,在WebContent、WEB-INF及src下分别有db1.properties,db2.properties,db3.properties三个文件。

 

在Servlet中使用ServletContent获取资源文件时,常用的方法有:

1.getResourceAsStream(path)

path即资源文件的路径写法:

(1)如果资源文件放在src下的某个包下面:/WEB-INF/classes/包名/文件名

例获取如上图src下的servlet.study包下的db3.properties文件,写法:

InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/servlet/study/db3.properties");

(2)如果资源文件放在WebContent即Web根目录下面:/文件名(这里以eclipse中的web项目为例,和WebRoot是一个道理)

例获取如上图WebContent下的db1.properties文件,写法:

InputStream in=this.getServletContext().getResourceAsStream("/db1.properties");

(3)如果资源文件放在WEB-INF下面:/WEB-INF/文件名

例获取如上图WEB-INF下的db2.properties文件,写法:

InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/db2.properties");

2.getRealPath(path)

此方法的path是文件的绝对路径

例获取如上图src下的servlet.study包下的db3.properties文件,写法:

String path=this.getServletContext().getRealPath("/WEB-INF/classes/servlet/study/db3.properties");

 

posted @ 2019-01-09 16:13  肥猫桂子  阅读(1342)  评论(0编辑  收藏  举报