spring boot监听在线人数

2021-05-14 15:28

阅读:651

标签:sys   package   int   span   public   设置   import   ali   ESS   

1.创建监听器类

package org.jcut.config;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class UserStatisticsListener implements HttpSessionListener {
    public static int count = 0;    

    @Override    

    public void sessionCreated(HttpSessionEvent se) {        

    System.out.println("创建session");        

    count ++;    

    }    

    @Override    

    public void sessionDestroyed(HttpSessionEvent se) {        

    System.out.println("销毁session");        

    count --;    

    }
}

2.spring boot启动类中加入扫描监听器类注解

@ServletComponentScan(basePackages = "org.jcut.config")

3.创建controller层

package org.jcut.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcut.config.UserStatisticsListener;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/UserListener")
public class UserListenerController {
    @RequestMapping("/logUser")    

    public String logUser(HttpServletRequest request, HttpServletResponse response){        

    request.getSession().setAttribute("name",request.getParameter("name"));
    return request.getParameter("name")+"登录成功!当前在线用户人数是:"+ UserStatisticsListener.count;    

    }    

    @RequestMapping("/logOut")    

    public String logOut(HttpServletRequest request, HttpServletResponse response){        

    request.getSession().invalidate();        

    return request.getParameter("name")+"登出成功!当前在线用户人数是:"+UserStatisticsListener.count;    

    }
}

4.注意事项

1.设置的session属性才算创建一个session,只要浏览器不关闭这个sessionid就不会改变
2.当浏览器关闭时再去访问创建session又会重新创建一个session
3.服务器关闭或重启session会被注销

 

spring boot监听在线人数

标签:sys   package   int   span   public   设置   import   ali   ESS   

原文地址:https://www.cnblogs.com/huqi96/p/13124208.html


评论


亲,登录后才可以留言!