Web应用一般有两种资源文件,相对独立的用properties文件,剩余的用xml文件。下面的访问资源文件的代码需要背过,代码如下:
第一种:
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//针对获取的url是因为ServletContext所获取的resource为tomcat编译后的在classes的各个servlet类,因此不是src下的类。获取到的文件流,用Properties这个类去接受,这个类专门接受后缀为properties的文件,内部数据结构为Map.
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name" );
String password= pros.getProperty("password");
第二种:
String path = this.getServletContext.getRealPath("/WEB-INF/classes/db.properties");
//返回给资源的绝对路径,这样就可以用传统就java代码了
FileInputStream in = new FileInputStream(path);
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name" );
String password= pros.getProperty("password");
还有就是在web项目中,如果没有使用servlet的情况下,我们如果直接是将servletContext直接传过来相对来时不妥,这是时候我们就需要用到类装载器来获取资源文件,这个时候需要弄清楚类装载器的生命周期。代码如下:
//这样能直接获取到更新后的资源文件,如果是这样是不能获取更新后的资源文件,代码如下:
//InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
String path = UserDao.class.getClassLoader().getResource("db.properties")getPath();
FileInputStream in = new FileInputStream(path);
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name" );
String password= pros.getProperty("password");
ServlertContext与类加载器获取Web应用中的资源文件
最新推荐文章于 2025-05-08 19:01:33 发布