1. 获取到整个 web 应用的配置信息
string url=this.getServletContext().getInitParameter("url");
String username=this.getServletContext().getInitParameter("username");
String password=this.getServletContext().getInitParameter("password");
2.实现 servlet 转发
this.getServletContext().setAttribute("data","serlvet数据转发”);
RequestDispatcherrd=this.getServletContext().getRequestDispatcher("/viewdata.jsp");
rd.forward(request,response);
3. 读取资源文件
在实际开发中,用作资源文件的文件类型,通常是:xml、properties,而读取xml 文件必然要进行 xml文档的解析,所以以下例子只对 properties 文件进行读取(在一个 web 工程中,只要涉及到写地址,建议最好以/开头)
在 web 工程中,我们一般来说,是不能采用传统方式读取配置文件的,因为相对的是jvm 的启动目录(tomcat 的 bin 目录),所以我们要使用 Web 绝对目录来获取配置文件的地址。
第一种:使用ServletContext的getResourceAsStream 方法:返回资源文件的读取字节流。
InputStream in=this.getServletContext().getResourceAsstream("/WEB-INF/classes/db.properties");
Properties prop = newProperties();
prop.load(in);
String url =prop.getProperty("url");
第二种:使用ServletContext的getRealPath 方法,获得文件的完整绝对路径 path,再使用字节流读取 path 下的文件。
String path=this.getServletContextO.getRealPath("/WEB-INF/classes/db.properties");
String filename =path.substring(path.1astIndexOf("\\")+1);
//相比第一种方法的好处是,除了可以获取数据,还可以获取资源文件的名称
FileInputstream in = newFileInputStream(path);
Properties prop= newProperties();
prop.load(in);
String url =prop.getProperty("url");