监听器案例----统计在线人数

监听器案例----统计在线人数_第1张图片


MyServletContextListener:

package app.java.listener.demo;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener {
	/**
	 * 完成在线人数统计的初始化工作.
	 */
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		context.setAttribute("sums", 0);
	}
	
	public void contextDestroyed(ServletContextEvent arg0) {}

}
MyHttpSessionListener

package app.java.listener.demo;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyHttpSessionListener implements HttpSessionListener {
	/**
	 * 创建Session表示人数增加一个.
	 *  * 在该方法中,获取ServletContext对象.
	 *  * 修改ServletContext对象的"sums"属性值.(+1)
	 *  * 将修改后的"sums"属性值,重新放回去.
	 */
	public void sessionCreated(HttpSessionEvent se) {
		ServletContext context = se.getSession().getServletContext();
		int sums = (Integer)context.getAttribute("sums");
		sums = sums + 1;
		context.setAttribute("sums", sums);
	}
	/**
	 * 销毁Session表示人数减少一个.
	 *  * 在该方法中,获取ServletContext对象.
	 *  * 修改ServletContext对象的"sums"属性值.(-1)
	 *  * 将修改后的"sums"属性值,重新放回去.
	 */
	public void sessionDestroyed(HttpSessionEvent se) {
		ServletContext context = se.getSession().getServletContext();
		int sums = (Integer)context.getAttribute("sums");
		sums = sums - 1;
		context.setAttribute("sums", sums);
	}

}
DemoServlet

package app.java.listener.demo;

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;
import javax.servlet.http.HttpSession;
/**
 * 当前servlet用于统计在线人数
 */
public class DemoServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("test/html charset = utf-8");

		//用于激活sessionlistener
		HttpSession session = request.getSession();
		session.setAttribute("mingjiao", "zhangwuji");
		System.out.println("人数增加了。。。");
		
		// 将统计的在线人数显示在客户端页面即可
		//1 获取ServletContext对象
		ServletContext context = getServletContext();
		
		//2 从servletContext对象中,获取在线统计人数
		int sums = (Integer)context.getAttribute("sums");
		
		//3将在线统计人数响应到客户端页面中
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("当前在线人数为:"+sums);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
xml:

  	app.java.listener.demo.MyServletContextListener
  
  
  	app.java.listener.demo.MyHttpSessionListener
  






你可能感兴趣的:(JavaWeb)