美文网首页
一、理解监听器的作用

一、理解监听器的作用

作者: lifeline张 | 来源:发表于2018-07-18 08:05 被阅读0次

    一、Listener

    • Listener是Servlet的监听器
    • 监听客户端的请求和服务器端的操作
    • 通过实现Listener接口的类可以在特定事件(Event)发生时,自动激发一些操作

    二、HttpSessionBindingListener

    当一个实现了该接口的对象被捆绑到session中或者从session中被解放的时候启用此监听。
    关键点:

    • 创建类实现HttpSessionBindingListener接口
    • valueBound()
    • valueUnbound()
    • 不需要在web.xml中配置监听器
    • 监听范围:一对一

    比如User这个类实现了该接口,则当这个对象被捆绑到session或者从session中被解除捆绑的时候启用此监听器。当被捆绑的时候,会自动进入valueBound()方法;当解除绑定的时候,会自动进入valueUnbound()方法。

    三、实例

    需求:统计在线人数;
    实体类User:

    package cn.kgc.pojo;
    
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSessionBindingListener;
    
    import cn.kgc.util.Constants;
    
    public class User implements HttpSessionBindingListener{
        private int id;
        private String userName;
        private String password;
        private String email;
        
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        
        // 当User对象放进session时(一个用户登录),会自动进入该方法
        public void valueBound(HttpSessionBindingEvent event) {
            Constants.USER_COUNT ++;
        }
        
        // session失效(某个用户注销)、超时、手动地在session中把某个属性移除
        public void valueUnbound(HttpSessionBindingEvent event) {
            Constants.USER_COUNT --;
        }
        
    
    }
    

    统计人数工具类,在该类中只有一个静态变量来统计人数:

    package cn.kgc.util;
    
    // 在线用户人数
    public class Constants {
        public static int USER_COUNT = 0;
    }
    
    

    登录页面:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'login.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
        <form action="doLogin.jsp" method="post">
           用户名:<input type="text" name="userName"/>
           <input type="submit" value="登录"/>
        </form>
      </body>
    </html>
    
    

    登录数据处理页面:

    <%@page import="cn.kgc.pojo.User"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'doLogin.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
       <%
            String userName = request.getParameter("userName");
            if (userName == null || userName.equals("")) {
                response.sendRedirect("login.jsp");
            } else {
                User user = new User();
                user.setUserName(userName);
                // 走到这一步的时候监听器就会启动了
                session.setAttribute("user", user);
                response.sendRedirect("online.jsp");
            }
        %>
      </body>
    </html>
    

    登录进来页面:

    <%@page import="cn.kgc.pojo.User"%>
    <%@page import="cn.kgc.util.Constants"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'online.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
      <%
          User user = null;
          if (session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
          } else {
           user = (User)session.getAttribute("user");
       %>
              欢迎你,<%=user.getUserName() %>
              当前在线人数为:<%=Constants.USER_COUNT %>
              <a href="loginout.jsp">离开</a>
        <%} %>
      </body>
    </html>
    

    离开页面:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'loginout.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
        <%
            // 离开、注销
            session.invalidate();
         %>
      </body>
    </html>
    

    运行结果:
    当登录一个人之后,会在online页面显示当前在线人数,当换一个浏览器登录之后,登录人数改变。

    相关文章

      网友评论

          本文标题:一、理解监听器的作用

          本文链接:https://www.haomeiwen.com/subject/tsbnpftx.html