spring boot监听在线人数
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会被注销