ServletContext:
1)是服务器端的一块公共存储区域,可供所有客户存取数据(全局区域);
模型图:
2)一个web应用程序只有一个ServletContext;
3)在Servlet中,获取ServletContext:(2种方法)
ServletContext servletContext = this.getServletContext();
ServletContext servletContext1 = req.getSession().getServletContext();
4)设值/取值和删除:
servletContext.setAttribute("count", 1); //设值
servletContext.getAttribute("count"); //取值
servletContext.removeAttribute("count"); //删除
5)ServletContext用法:
a、可以读取全局配置文件:
配置文件:
<context-param> <!-- 配置全局变量 所有ServletContext都可以访问 -->
<param-name>name</param-name>
<param-value>char</param-value>
</context-param>
Servlet中代码:
String value = this.getServletContext().getInitParameter("name");
b、读取资源文件:
资源文件放于根目录下,和WEB-INF同级:
InputStream is = this.getServletContext().getResourceAsStream("db.properties");
Properties pros = new Properties();
pros.load(is);
如果资源文件在src下:
InputStream is = ContextServlet.class.getClassLoader().getResourceAsStream("db.properties");
Properties pros = new Properties();
pros.load(is);
c、作为全局变量的应用:网站计数器/网络聊天室;
6)servlet局部变量:
<servlet>
<servlet-name>configServlet</servlet-name>
<servlet-class>servlet.ConfigServlet</servlet-class>
<!-- 局部变量设置 -->
<init-param>
<param-name>name</param-name>
<param-value>char</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>configServlet</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>
Servlet代码:
public class ConfigServlet extends HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException {
String value = config.getInitParameter("name");
System.out.println(value);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
7)ServletContext生命周期:和服务器一致,即服务器启动时自动创建该对象,服务器关闭后自动销毁该对象;
8)三种存储数据的方式:request/session/ServletContext:
存储时间长短:ServletContext > session(会话时间范围内) > request(请求时间范围内)