1、ServletContext是服务器端一块公共的存储区域,可供所有开户存储数据,全局区域。
一个web应用程序只有一个ServletContext。
2、在servlet中获取ServletContext
ServletContext servletContext = this.getServletContext();
ServletContext servletContext1 = req.getSession().getServletContext();
3、设值、取值、删除
servletContext.setAttribute("name", "books");
servletContext.getAttribute("name");
servletContext.removeAttribute("name");
4、用处:
a)可以读取全局配置文件
<context-param>
<param-name>name</param-name>
<param-value>yuchao</param-value>
</context-param>
Servlet中代码:
ServletContext ct = this.getServletContext();
String value = ct.getInitParameter("name");
b) 读取资源文件
资源文件放于根目录下 和WEB-INF同级
InputStream in = ct.getResourceAsStream("db.properties");
Properties pro = new Properties();
pro.load(in);
out.print(pro.getProperty("driver")+"<br/>");
out.print(pro.getProperty("url")+"<br/>");
如果资源在src下:
//类加载器
InputStream in = MyServletContext.class.getClassLoader().getResourceAsStream("db.properties");
Properties pro = new Properties();
pro.load(in);
out.print(pro.getProperty("driver")+"<br/>");
out.print(pro.getProperty("url")+"<br/>");
c) 作为全局变量的运用;网站计数器,网络聊天室
5、servletContext生命周期,和服务器同生共死。
6、Request、Session、ServletContext/aoolication
存放时间长短:
ServletContext最长,和服务器一样
Session次子,在一个会话范围(失效时间)
Request 请求范围