Listener

1. 步骤

  1. 编写一个类,实现监听器的接口

    package com.gs.listener;
    
    import jakarta.servlet.http.HttpSessionEvent;
    import jakarta.servlet.http.HttpSessionListener;
    
    /**
     * @author admin
     * @date 2021/9/8 10:54 下午
     */
    public class SessionListener implements HttpSessionListener {
        @Override
        public void sessionCreated(HttpSessionEvent se) {
            Integer onlineCount = (Integer) se.getSession().getServletContext().getAttribute("onlineCount");
            if (onlineCount == null) {
                onlineCount = 1;
            } else {
                onlineCount += 1;
            }
            se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            Integer onlineCount = (Integer) se.getSession().getServletContext().getAttribute("onlineCount");
            if (onlineCount == null) {
                onlineCount = 0;
            } else {
                onlineCount -= 1;
            }
            se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
        }
    }
    
  2. web.xml中配置Listener

    <listener>
      <listener-class>com.gs.listener.SessionListener</listener-class>
    </listener>
    
  3. 测试

    <h1>当前在线人数为:<span style="color: aqua">${onlineCount}</span>人</h1>
    

    Tomcat初跑时,可能会存在几个Session。Redeploy即可。

2. 小案例

用户登陆后才能进入主页,注销后就进不去主页。

  1. 用户登陆之后,向Session中放入用户数据
  2. 进入主页的时候判断用户是否已经登陆,在过滤器中实现
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;

if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
    response.sendRedirect("/error.jsp");
}

chain.doFilter(request,response);
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-11-26 20:03:31

results matching ""

    No results matching ""