概括:

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 监听器统计当前在线人数,拿来即用,不忽悠

2018年09月30日 19:35:25 农民奔小康 阅读数 3440
 
版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明。

原理就是很简单,就是利用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.  
    }

开始测试吧

springboot使用HttpSessionListener 监听器统计当前在线人数的更多相关文章

  1. Servlet监听器统计网站在线人数

    本节我们利用 Servlet 监听器接口,完成一个统计网站在线人数的案例.当一个用户登录后,显示欢迎信息,同时显示出当前在线人数和用户名单.当用户退出登录或 Session 过期时,从在线用户名单中删 ...

  2. Servlet监听器统计在线人数

    监听器的作用是监听Web容器的有效事件,它由Servlet容器管理,利用Listener接口监听某个执行程序,并根据该程序的需求做出适应的响应. 例1 应用Servlet监听器统计在线人数. (1)创 ...

  3. 监听器的配置,绑定HttpSessionListener监听器的使用

    监听器的配置,绑定 <listener> <listener-class>监听器的全路径</listener-class> </listener> Se ...

  4. java-web项目:用servlet监听器实现显示在线人数

    1.创建一个监听器 package com.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpS ...

  5. 用HttpSessionListener与HttpSessionBindingListener实现在线人数统计

    在线人数统计方面的实现,最初我的想法是,管理session,如果session销毁了就减少,如果登陆用户了就新增一个,但是如果是用户非法退出,如:未注销,关闭浏览器等,这个用户的session是管理不 ...

  6. [转]用HttpSessionListener与HttpSessionBindingListener实现在线人数统计

    原文链接:http://www.cnblogs.com/shencheng/archive/2011/01/07/1930227.html 下午比较闲(其实今天都很闲),想了一下在线人数统计方面的实现 ...

  7. javaEE之--------统计站点在线人数,安全登录等(观察者设计模式)

    整体介绍下:  监听器:监听器-就是一个实现待定接口的普通Java程序,此程序专门用于监听别一个类的方法调用.都是使用观察者设计模式. 小弟刚接触这个,做了些简单的介绍.大神请绕道,技术仅仅是一点点, ...

  8. java监听器之实现在线人数显示

    在码农的世界里只有bug才能让人成长,The more bugs you encounter, the more efficient you will be! java中的监听器分为三种:Servle ...

  9. 使用session的监听器获取当前在线人数

    1首先在web.xml中配置Session的监听器 2创建监听器并且继承HttpSessionListener 3.在jsp中导入监听器 4.获取当前在线人数 5.配置到公共网络(使用natapp的免 ...

随机推荐

  1. AttributeError: module ‘select’ has no attribute 'epoll’

    场景:mac 下导入的 ‘select’ 包 import select,然后在 主函数 中创建的 epoll 对象 epl = select.epoll(),运行报错如下 Traceback (mo ...

  2. FZU Monthly-201909 tutorial

    FZU Monthly-201909 tutorial 题目(难度递增) easy easy-medium medium medium-hard hard 思维难度 AB CD EF G H A. I ...

  3. SyntaxError: expected expression, got ")" void() : 1: 5

    这个错误的意思是: 本来希望得到 一个 表达式, 缺得到了 ), 凡是 这样的错误, 就是 函数 在当前位置, 需要一个参数! 参数没有给, 就 输入 ) 右括号了! 错误位置 1: 5, 就是 指 ...

  4. Android ConstraintLayout 小记

    * 可以圆形定位view之间的位置,通过View的中心,来定位不同半径和弧度的距离. layout_constraintCircle : references another widget id la ...

  5. pycharm把制表符(tab)转换为空格(PEP8)

    pycharm把制表符转换为4个空格 pycharm显示空格

  6. H5+js调用相机

    在机缘巧合之下,了解到用HTML5和javascript调用摄像头来实现拍照功能,今天就把大致原理写下来.页面布局很简单,就是一个input标签,两个HTML5元素video.canvas和一个but ...

  7. Hadoop的三种调度器FIFO、Capacity Scheduler、Fair Scheduler(转载)

    目前Hadoop有三种比较流行的资源调度器:FIFO .Capacity Scheduler.Fair Scheduler.目前Hadoop2.7默认使用的是Capacity Scheduler容量调 ...

  8. 两个字符串对比提升比较性能用 StringComparison.OrdinalIgnoreCase

    如果用string.ToLower() 或者 string.ToUpper()字符串在进行大小写转换时会消耗额外的性能 用这个比较性能更好 StringPwd1.Equals(Md5(PassWord ...

  9. c++ extra qualification

    原 c++ extra qualification 2013年01月15日 10:04:52 沈纵情 阅读数 9728   运行代码时候遇到了如下错误: extra qualification ‘Co ...

  10. WebGL学习笔记(八):光照

    局部光照与全局光照 局部光照 只考虑光源到模型表面的照射效果,运算量较小: 全局光照 考虑到环境中所有表面和光源相互作用的照射效果,即让没有直接受光照射的位置也会受周围反射光的影响,运算量较大: Ph ...