码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot监听在线人数

时间:2020-06-14 12:49:25      阅读:106      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!