https://www.cnblogs.com/fjdingsd/p/4846727.html
ServletContext类中有这么四个方法:
getRealPath(String path)
getResource(String path)
getResourceAsStream(String path)
getResourcePaths(String path)
这四个方法都使用web工程下某个web资源路径的字符串表现形式作为参数,而每个方法返回不同的类型,我们通过这四个方法之一可以获取某个资源,并对其进行读取和修改操作。
假设我们的【myservlet】web工程中有一个数据库的配置文件:database.properties,在这个数据库中已经有了一些参数,而我们在web工程中希望读取这个配置文件中的有关信息:
getResourceAsStream(String path)
先来看看ServletContext中的getResourceAsStream()方法,这个方法返回InputStream对象。由于我们的配置文件为properties文件,所以可以用Properties对象来装载这个输入流,代码如下:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream in = context.getResourceAsStream("/database.properties");
Properties prop = new Properties();
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
getRealPath()
接下来看看ServletContext中的getRealPath()方法,这个方法返回String对象。由于我们的配置文件为properties文件ÿ