jsp中通过上下文对象统计当前在线人数
1、上下文对象的特点: 唯一性:一个web应用只有一个上下文对象 全局性:上下文对象的数据可以在整个web应用程序中被访问和操作 通过这两个特点:一般在网站中统计当前在线人数时常用

2、如何去获取上下文对象: 1.通过GenericServlet提供的getSerletContext()可以获得 2.通过HttpServlet提供的getServletContext()可以获得 3.通过HttpSession提供的getServletContext()可以获得 4.通过FilterConfig提供的getServletContext()可以获得

3、servlet上下文的作用: 1.通过setAttribute()设置绑定值 2.通过removeAttribute()删除绑定 3.通过getAttribute()

4、程序需要导入的包
import java.io.IOException;import java.io.PrintWriter;
import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
/** * 通过上下文对象统计当前在线人数 * @author Administrator * */

5、继承HttpServlet类或者实现servlet接口
public class ContextServlet01 extends HttpServlet{ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); //获取上下文对象 ServletContext context=getServletContext();

6、//定义一个统计变量 Object count=context.getAttribute("count"); if(count==null){ context.setAttribute("count", context.getInitParameter("count")); }else{ context.setAttribute("count", Integer.parseInt(count.toString())+1); } out.println("当前在线人数:"+context.getAttribute("count")); out.close(); }}
