1.监听器 Listener
【JavaWeb】 三大组件之监听器 Listener
1. 概念
监听域对象的创建和销毁 监听域对象的属性操作。(增加、修改、删除) |
2. 分类
监听域对象的创建和销毁 ServletRequestListener HttpSessionListener ServletContextListener 监听域对象的属性操作 ServletRequestAttributeListener HttpSessionAttributeListener ServletContextAttributeListener |
3. 典型应用
4. 统计在线人数实现步骤(演示)
1. 创建一个Listener监听器的类,监听session创建和销毁。实现HttpSessionListener
/** * 监听session的创建 */ @WebListener public class OnlineNumListener implements HttpSessionListener{
public OnlineNumListener() { } /** * 监听session对象创建调用,在线人数+1 */ @Override public void sessionCreated(HttpSessionEvent se) { // 从application作用域中获取在线人数 ServletContext application=se.getSession().getServletContext(); if(application.getAttribute("count")!=null){ // 在线人数+1 int count =(int)application.getAttribute("count"); application.setAttribute("count",count+1); }else{ application.setAttribute("count",1); } } /** * 监听session销毁调用,在线人数-1 */ @Override public void sessionDestroyed(HttpSessionEvent se) { // 从application作用域中获取在线人数 ServletContext application=se.getSession().getServletContext(); int count =(int)application.getAttribute("count"); application.setAttribute("count",count-1); } } |
2. 编写jsp页面展示在线人数
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <h2>在线人数:${count}</h2> <a href="exitServlet">退出</a> </body> </html> |
3. 退出
@WebServlet(name = "ExitServlet", value = "/exitServlet") public class ExitServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); //销毁 session session.invalidate(); } } |