ServletContext对象

1. ServletContext对象代表整个web应用

2. ServletContext对象是一个域对象(可以存储数据的对象)

3. ServletContext对象的内部维护了一个map集合 key是String类型 value是Object类型


1. 将ServletContext作为域对象 实现多个Servlet对象共享案例

// 存数据

// 1. 获得ServletContext对象

ServletContext context = getServletContext();

// 2. 存入域 

context.setAttribute("name",Object) ;

// 3. 取数据 

Object obj = (Object)getServletContext().getAttribute("name");

2. 获取web应用的初始化参数

getContext().getInitParameter("name") ;

3. 统计一个web应用的访问量

在 context 域中维护一个 count 变量

ServletContext context = getServletContext();

Integer count = (Integer) context.getAttribute("count");

if(count==null) count=0;

count++;

context.setAttribute("count",count) ;

response.getWriter().writer("count=" + count) ;

4. 实现Servlet转发 

ServletContext context = getServletContext();

RequestDispatcher dispatcher = context.getRequestDispatcher("/a.jsp");

dispatcher.forward(request,response);

posted on 2012-04-27 22:54  Knuth_档案  阅读(287)  评论(0编辑  收藏  举报

导航