学习笔记 · JavaWeb里绑定对象的监听器HttpSessionBindingListener

JavaWeb里绑定对象的监听器HttpSessionBindingListener


作者:氯磷Rolin

其他: JavaWeb持久化监听器-HttpSessionActivationListener

HttpSessionBindingListener

作用

HttpSessionBindingListener用于监听对象与Session的绑定与解除绑定的动作

  • 一个实现了HttpSessionBindingListener接口的类,其实例化对象可以用于精准监听某一个参数是否绑定于Session里,如果Session加入了该对象,则类调用valueBound()方法,如果该对象从Session中被移除或Session失效,则调用valueUnbound()方法
  • 比如 当有用户登陆时,我们将含有该用户的HttpSessionBindingListener监听器的对象放入Session中,当该用户退出浏览器或者超时未在连接时,服务器会自动把当前Session删除作废,HttpSessionBindingListener通过bound和unbound就可以监听到当前用户是否还在线上
  • HttpSessionListener是针对整个Session参数变化而监听的,HttpSessionBindingListener是针对Session里某一个值进行监听,进一步的,我们可以在监听类里实现一些对于数据的操作

用法

  • HttpSessionBindingListener监听器不需要注册,但是需要实例化(new)后才可以使用
  • 简单的HttpSessionBindingListener实现方法:
    1. 新建类 OnlineBindingListener ,实现HttpSessionBinding接口并构造一个含有参数的方法,用于记录某用户是否在线
      package com.Rolin.Listener;
      import javax.servlet.http.*;
      public class OnlineUserListener implements HttpSessionBindingListener {
          String username;
          public OnlineUserListener(String username) {
              this.username = username;
          }
          @Override
          public void valueBound(HttpSessionBindingEvent event) {
              System.out.println("This object's Bound :"+username);
          }
          @Override
          public void valueUnbound(HttpSessionBindingEvent event) {
              System.out.println("This object's Unbound :"+username);
          }
      }
      
    2. 新建一个用户界面,使得能够进行登录和注销操作
      		<%@ page contentType="text/html;charset=UTF-8" language="java" %>
      		<html>
      		  <head>
      		    <title>HSBL绑定监听</title>
      		  </head>
      		  <body>
      		    <form action="doLogin" method="post">
      		      <input type="text" name="username" />
      		      <input type="submit" value="Login"/>
      		      <p><a href="/logout">点击注销</a></p>
      		    </form>
      		  </body>
      		</html>
      
      页面如下:
      在这里插入图片描述
    3. 在Servlet中调用session.setAttribute()方法,将HttpSessionBindingListener对象放入Session中,完成绑定
      • 登录Servlet:
        @WebServlet("/doLogin")
        public class doLogin extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                request.setCharacterEncoding("UTF-8");
                String name = request.getParameter("username");
                HttpSession session = request.getSession();
                session.setAttribute("OnlineUserListener",new OnlineUserListener(name));
                response.sendRedirect("/");
            }
        
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doPost(request,response);
            }
        }
        
      • 注销Servlet:
        @WebServlet("/logout")
        public class logout extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            }
            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                HttpSession session = request.getSession();
                session.removeAttribute("OnlineUserListener");
            }
        }
        
    4. 运行Tomcat,测试代码
      在这里插入图片描述

具体实例:当前在线用户数量

  1. 创建交互界面,使得可以登录、注销和显示当前在线人数

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>HSBL绑定监听</title>
      </head>
      <body>
        <form action="doLogin" method="post">
          <input type="text" name="username" />
          <input type="submit" value="Login"/>
          <p><a href="/logout">点击注销</a></p>
          <p>当前用户在线人数:${number}</p>
        </form>
      </body>
    </html>
    

    在这里插入图片描述

  2. 创建 OnlineUserListener类,实现HttpSessionBindingListener接口,用于监听Session参数,并且把数据存入到静态属性中

    package com.Rolin.Listener;
    import javax.servlet.http.*;
    public class OnlineUserListener implements HttpSessionBindingListener {
        String username;
        static int num;
        public static int getNum() {
            return num;
        }
        static {
            num = 0; //服务器启动时初始化在线人数
        }
        public OnlineUserListener(String username) {
            this.username = username; //构造函数
        }
        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            System.out.println("This object's Bound :"+username);
            num++;  //增加
        }
        @Override
        public void valueUnbound(HttpSessionBindingEvent event) {
            System.out.println("This object's Unbound :"+username);
            num--;
        }
    }
    
  3. 创建doLogin和doLogout类,处理登录和注销请求

  • doLogin类

    @WebServlet("/doLogin")
    public class doLogin extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            String name = request.getParameter("username");
            HttpSession session = request.getSession();
            session.setAttribute("OnlineUserListener",new OnlineUserListener(name));
            response.sendRedirect("/");
            session.setAttribute("number",OnlineUserListener.getNum());
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
        }
    }
    
  • doLogout类

    @WebServlet("/logout")
    public class logout extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            session.removeAttribute("OnlineUserListener");
            session.setAttribute("number", OnlineUserListener.getNum());
        }
    }
    
  1. 执行代码,当用户登录时,在线人数变为1,当用户注销时,在线人数变为0.
    在这里插入图片描述
    在这里插入图片描述

在这里插入图片描述



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值