springboot使用HttpSessionListener 监听器统计当前在线人数

时间:2024-03-03 18:28:33

概括:

request.getSession(true):若存在会话则返回该会话,否则新建一个会话。

request.getSession(false):若存在会话则返回该会话,否则返回NULL

 

https://blog.csdn.net/qq_38091831/article/details/82912831

原理就是很简单,就是利用HttpSessionListener 监听session的创建和销毁,然后定义个静态变量存储在线人数的变化。 说两种方式,第一种是使用配置类,第二种是使用@WebListener注解,都差不多 方式一:使用配置类 1.创建session监听器 package com.sdsft.pcweb.common.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyHttpSessionListener implements HttpSessionListener { public static int online = 0; @Override public void sessionCreated(HttpSessionEvent se) { System.out.println("创建session"); online ++; } @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println("销毁session"); online --; } } 2.配置类 package com.sdsft.pcweb.common.config; import com.sdsft.pcweb.common.listener.MyHttpSessionListener; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MywebConfig implements WebMvcConfigurer { @Bean public ServletListenerRegistrationBean listenerRegist() { ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean(); srb.setListener(new MyHttpSessionListener()); System.out.println("listener"); return srb; } } 3.控制器 package com.sdsft.pcweb.controller; import com.sdsft.pcweb.common.entity.CommonResult; import com.sdsft.pcweb.common.enums.ResultEnum; import com.sdsft.pcweb.common.listener.MyHttpSessionListener; import com.sdsft.pcweb.service.LoginService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * LoginController class * @author zcz * @date 2018/09/20 */ @RequestMapping("/userInfo") @RestController public class LoginController { private static Logger logger = LoggerFactory.getLogger(LoginController.class); /** * 登录 */ @PostMapping("/Login") public void getUserByUserNameAndPassword(String username, String password, HttpSession session) { logger.info("用户【"+username+"】登陆开始!"); if("admin".equals(username) && "123456".equals(password)){ session.setAttribute("loginName",username); logger.info("用户【"+username+"】登陆成功!"); }else{ logger.info("用户【"+username+"】登录失败!"); } } /** *查询在线人数 */ @RequestMapping("/online") public Object online() { return "当前在线人数:" + MyHttpSessionListener.online + "人"; } /** * 退出登录 */ @RequestMapping("/Logout") public CommonResult Logout( HttpServletRequest request) { logger.info("用户退出登录开始!"); HttpSession session = request.getSession(false);//防止创建Session if(session != null){ session.removeAttribute("loginName"); session.invalidate(); } logger.info("用户退出登录结束!"); return new CommonResult(ResultEnum.SUCCESS.getCode(), "退出成功!"); } /** * 判断session是否有效 * @param httpServletRequest * @return */ @RequestMapping("/getSession") public String getSession(HttpServletRequest httpServletRequest) { HttpSession session = httpServletRequest.getSession(); String loginName = (String) session.getAttribute("loginName"); if (StringUtils.isNotBlank(loginName)) { return "200"; } return ""; } } 测试一下吧 方式二:使用@WebListener注解 1.创建监听器,加注解@WebListener package com.sdsft.pcweb.common.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener public class MyHttpSessionListener implements HttpSessionListener { public static int online = 0; @Override public void sessionCreated(HttpSessionEvent se) { System.out.println("创建session"); online ++; } @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println("销毁session"); online --; } } 2.控制器 package com.sdsft.pcweb.controller; import com.sdsft.pcweb.common.entity.CommonResult; import com.sdsft.pcweb.common.enums.ResultEnum; import com.sdsft.pcweb.common.listener.MyHttpSessionListener; import com.sdsft.pcweb.service.LoginService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * LoginController class * @author zcz * @date 2018/09/20 */ @RequestMapping("/userInfo") @RestController public class LoginController { private static Logger logger = LoggerFactory.getLogger(LoginController.class); /** * 登录 */ @PostMapping("/Login") public void getUserByUserNameAndPassword(String username, String password, HttpSession session) { logger.info("用户【"+username+"】登陆开始!"); if("admin".equals(username) && "123456".equals(password)){ session.setAttribute("loginName",username); logger.info("用户【"+username+"】登陆成功!"); }else{ logger.info("用户【"+username+"】登录失败!"); } } /** *查询在线人数 */ @RequestMapping("/online") public Object online() { return "当前在线人数:" + MyHttpSessionListener.online + "人"; } /** * 退出登录 */ @RequestMapping("/Logout") public CommonResult Logout( HttpServletRequest request) { logger.info("用户退出登录开始!"); HttpSession session = request.getSession(false);//防止创建Session if(session != null){ session.removeAttribute("loginName"); session.invalidate(); } logger.info("用户退出登录结束!"); return new CommonResult(ResultEnum.SUCCESS.getCode(), "退出成功!"); } /** * 判断session是否有效 * @param httpServletRequest * @return */ @RequestMapping("/getSession") public String getSession(HttpServletRequest httpServletRequest) { HttpSession session = httpServletRequest.getSession(); String loginName = (String) session.getAttribute("loginName"); if (StringUtils.isNotBlank(loginName)) { return "200"; } return ""; } } 3.启动类加@ServletComponentScan注解,这样才能在程序启动时将对应的bean加载进来 package com.sdsft.pcweb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class PcwebApplication { public static void main(String[] args) { SpringApplication.run(PcwebApplication.class, args); } } 开始测试吧

 

 

springboot统计当前在线人数,springboot使用HttpSessionListener 监听器统计当前在线人数,拿来即用,不忽悠

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38091831/article/details/82912831

原理就是很简单,就是利用HttpSessionListener 监听session的创建和销毁,然后定义个静态变量存储在线人数的变化。

说两种方式,第一种是使用配置类,第二种是使用@WebListener注解,都差不多

方式一:使用配置类

1.创建session监听器

  1.  
    package com.sdsft.pcweb.common.listener;
  2.  
     
  3.  
    import javax.servlet.http.HttpSessionEvent;
  4.  
    import javax.servlet.http.HttpSessionListener;
  5.  
     
  6.  
    public class MyHttpSessionListener implements HttpSessionListener {
  7.  
     
  8.  
    public static int online = 0;
  9.  
    @Override
  10.  
    public void sessionCreated(HttpSessionEvent se) {
  11.  
    System.out.println("创建session");
  12.  
    online ++;
  13.  
    }
  14.  
     
  15.  
    @Override
  16.  
    public void sessionDestroyed(HttpSessionEvent se) {
  17.  
    System.out.println("销毁session");
  18.  
    online --;
  19.  
    }
  20.  
     
  21.  
    }

2.配置类

  1.  
    package com.sdsft.pcweb.common.config;
  2.  
     
  3.  
    import com.sdsft.pcweb.common.listener.MyHttpSessionListener;
  4.  
    import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
  5.  
    import org.springframework.context.annotation.Bean;
  6.  
    import org.springframework.context.annotation.Configuration;
  7.  
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  8.  
     
  9.  
    @Configuration
  10.  
    public class MywebConfig implements WebMvcConfigurer {
  11.  
    @Bean
  12.  
    public ServletListenerRegistrationBean listenerRegist() {
  13.  
    ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
  14.  
    srb.setListener(new MyHttpSessionListener());
  15.  
    System.out.println("listener");
  16.  
    return srb;
  17.  
    }
  18.  
    }

3.控制器

  1.  
    package com.sdsft.pcweb.controller;
  2.  
     
  3.  
    import com.sdsft.pcweb.common.entity.CommonResult;
  4.  
    import com.sdsft.pcweb.common.enums.ResultEnum;
  5.  
    import com.sdsft.pcweb.common.listener.MyHttpSessionListener;
  6.  
    import com.sdsft.pcweb.service.LoginService;
  7.  
    import org.apache.commons.lang3.StringUtils;
  8.  
    import org.slf4j.Logger;
  9.  
    import org.slf4j.LoggerFactory;
  10.  
    import org.springframework.beans.factory.annotation.Autowired;
  11.  
    import org.springframework.web.bind.annotation.PostMapping;
  12.  
    import org.springframework.web.bind.annotation.RequestMapping;
  13.  
    import org.springframework.web.bind.annotation.ResponseBody;
  14.  
    import org.springframework.web.bind.annotation.RestController;
  15.  
     
  16.  
    import javax.servlet.http.HttpServletRequest;
  17.  
    import javax.servlet.http.HttpSession;
  18.  
     
  19.  
    /**
  20.  
    * LoginController class
  21.  
    * @author zcz
  22.  
    * @date 2018/09/20
  23.  
    */
  24.  
    @RequestMapping("/userInfo")
  25.  
    @RestController
  26.  
    public class LoginController {
  27.  
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
  28.  
     
  29.  
    /**
  30.  
    * 登录
  31.  
    */
  32.  
    @PostMapping("/Login")
  33.  
    public void getUserByUserNameAndPassword(String username, String password, HttpSession session) {
  34.  
    logger.info("用户【"+username+"】登陆开始!");
  35.  
    if("admin".equals(username) && "123456".equals(password)){
  36.  
    session.setAttribute("loginName",username);
  37.  
    logger.info("用户【"+username+"】登陆成功!");
  38.  
    }else{
  39.  
    logger.info("用户【"+username+"】登录失败!");
  40.  
    }
  41.  
    }
  42.  
    /**
  43.  
    *查询在线人数
  44.  
    */
  45.  
    @RequestMapping("/online")
  46.  
    public Object online() {
  47.  
    return "当前在线人数:" + MyHttpSessionListener.online + "人";
  48.  
    }
  49.  
    /**
  50.  
    * 退出登录
  51.  
    */
  52.  
    @RequestMapping("/Logout")
  53.  
    public CommonResult Logout( HttpServletRequest request) {
  54.  
    logger.info("用户退出登录开始!");
  55.  
    HttpSession session = request.getSession(false);//防止创建Session
  56.  
    if(session != null){
  57.  
    session.removeAttribute("loginName");
  58.  
    session.invalidate();
  59.  
    }
  60.  
    logger.info("用户退出登录结束!");
  61.  
    return new CommonResult(ResultEnum.SUCCESS.getCode(), "退出成功!");
  62.  
    }
  63.  
     
  64.  
     
  65.  
    /**
  66.  
    * 判断session是否有效
  67.  
    * @param httpServletRequest
  68.  
    * @return
  69.  
    */
  70.  
    @RequestMapping("/getSession")
  71.  
    public String getSession(HttpServletRequest httpServletRequest) {
  72.  
    HttpSession session = httpServletRequest.getSession();
  73.  
    String loginName = (String) session.getAttribute("loginName");
  74.  
    if (StringUtils.isNotBlank(loginName)) {
  75.  
    return "200";
  76.  
    }
  77.  
    return "";
  78.  
    }
  79.  
     
  80.  
    }

测试一下吧

方式二:使用@WebListener注解

1.创建监听器,加注解@WebListener

  1.  
    package com.sdsft.pcweb.common.listener;
  2.  
     
  3.  
    import javax.servlet.http.HttpSessionEvent;
  4.  
    import javax.servlet.http.HttpSessionListener;
  5.  
    @WebListener
  6.  
    public class MyHttpSessionListener implements HttpSessionListener {
  7.  
     
  8.  
    public static int online = 0;
  9.  
    @Override
  10.  
    public void sessionCreated(HttpSessionEvent se) {
  11.  
    System.out.println("创建session");
  12.  
    online ++;
  13.  
    }
  14.  
     
  15.  
    @Override
  16.  
    public void sessionDestroyed(HttpSessionEvent se) {
  17.  
    System.out.println("销毁session");
  18.  
    online --;
  19.  
    }
  20.  
     
  21.  
    }

2.控制器

  1.  
    package com.sdsft.pcweb.controller;
  2.  
     
  3.  
    import com.sdsft.pcweb.common.entity.CommonResult;
  4.  
    import com.sdsft.pcweb.common.enums.ResultEnum;
  5.  
    import com.sdsft.pcweb.common.listener.MyHttpSessionListener;
  6.  
    import com.sdsft.pcweb.service.LoginService;
  7.  
    import org.apache.commons.lang3.StringUtils;
  8.  
    import org.slf4j.Logger;
  9.  
    import org.slf4j.LoggerFactory;
  10.  
    import org.springframework.beans.factory.annotation.Autowired;
  11.  
    import org.springframework.web.bind.annotation.PostMapping;
  12.  
    import org.springframework.web.bind.annotation.RequestMapping;
  13.  
    import org.springframework.web.bind.annotation.ResponseBody;
  14.  
    import org.springframework.web.bind.annotation.RestController;
  15.  
     
  16.  
    import javax.servlet.http.HttpServletRequest;
  17.  
    import javax.servlet.http.HttpSession;
  18.  
     
  19.  
    /**
  20.  
    * LoginController class
  21.  
    * @author zcz
  22.  
    * @date 2018/09/20
  23.  
    */
  24.  
    @RequestMapping("/userInfo")
  25.  
    @RestController
  26.  
    public class LoginController {
  27.  
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
  28.  
     
  29.  
    /**
  30.  
    * 登录
  31.  
    */
  32.  
    @PostMapping("/Login")
  33.  
    public void getUserByUserNameAndPassword(String username, String password, HttpSession session) {
  34.  
    logger.info("用户【"+username+"】登陆开始!");
  35.  
    if("admin".equals(username) && "123456".equals(password)){
  36.  
    session.setAttribute("loginName",username);
  37.  
    logger.info("用户【"+username+"】登陆成功!");
  38.  
    }else{
  39.  
    logger.info("用户【"+username+"】登录失败!");
  40.  
    }
  41.  
    }
  42.  
    /**
  43.  
    *查询在线人数
  44.  
    */
  45.  
    @RequestMapping("/online")
  46.  
    public Object online() {
  47.  
    return "当前在线人数:" + MyHttpSessionListener.online + "人";
  48.  
    }
  49.  
    /**
  50.  
    * 退出登录
  51.  
    */
  52.  
    @RequestMapping("/Logout")
  53.  
    public CommonResult Logout( HttpServletRequest request) {
  54.  
    logger.info("用户退出登录开始!");
  55.  
    HttpSession session = request.getSession(false);//防止创建Session
  56.  
    if(session != null){
  57.  
    session.removeAttribute("loginName");
  58.  
    session.invalidate();
  59.  
    }
  60.  
    logger.info("用户退出登录结束!");
  61.  
    return new CommonResult(ResultEnum.SUCCESS.getCode(), "退出成功!");
  62.  
    }
  63.  
     
  64.  
     
  65.  
    /**
  66.  
    * 判断session是否有效
  67.  
    * @param httpServletRequest
  68.  
    * @return
  69.  
    */
  70.  
    @RequestMapping("/getSession")
  71.  
    public String getSession(HttpServletRequest httpServletRequest) {
  72.  
    HttpSession session = httpServletRequest.getSession();
  73.  
    String loginName = (String) session.getAttribute("loginName");
  74.  
    if (StringUtils.isNotBlank(loginName)) {
  75.  
    return "200";
  76.  
    }
  77.  
    return "";
  78.  
    }
  79.  
     
  80.  
    }

3.启动类加@ServletComponentScan注解,这样才能在程序启动时将对应的bean加载进来

  1.  
    package com.sdsft.pcweb;
  2.  
    import org.springframework.boot.SpringApplication;
  3.  
    import org.springframework.boot.autoconfigure.SpringBootApplication;
  4.  
    import org.springframework.boot.web.servlet.ServletComponentScan;
  5.  
     
  6.  
    @SpringBootApplication
  7.  
    @ServletComponentScan
  8.  
    public class PcwebApplication {
  9.  
    public static void main(String[] args) {
  10.  
    SpringApplication.run(PcwebApplication.class, args);
  11.  
    }
  12.  
    }

开始测试吧