概括:

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. itext7 html转pdf实现

    公司最近做一个交易所项目,里面涉及一个需求就是将html模板,在填充数据后转换为pdf,这样防止数据更改,下面是具体实现 1 pom文件 <dependency> <groupId& ...

  2. java复制对象之深拷背

    在java开发中,有时我们需要复制对象,并且确保修改复制得到的对象不会影响原来的对象. 于是,有些人可能会写出类似以下的代码: public class CloneTest { public stat ...

  3. quartz 1.6.2之前的版本,定时任务自动停掉问题

    https://searchcode.com/codesearch/view/28831622/ Quartz 1.6.2 Release Notes This release contains a ...

  4. AES采用CBC模式128bit加密工具类

    写在前面 安全测试ECB模式过于简单需要改为CBC模式加密以下为工具类及测试 AESUtils.java package com.sgcc.mobile.utils; import sun.misc. ...

  5. fluid.io.load_inference_model 载入多个模型的时候会报错 -- [paddlepaddle]

    将多个模型部署到同一个服务时,会出现stack错误. 原因是program为全局. 改成这样,可以解决. solved by myself. for those who need it:use a n ...

  6. opencv马赛克python实现

    最近要实现opencv视频打马赛克,在网上找了一下基本是C++的实现,好在原理一样,下面给出python实现. 原理和注意点,我都写在注释里了 import cv2 ##马赛克 def do_mosa ...

  7. sql server 利用存储过程http请求调用URL链接访问方法

    sp_configure ; GO RECONFIGURE; GO sp_configure ; GO RECONFIGURE; GO EXEC sp_configure 'Ole Automatio ...

  8. wms证书配置操作

      1. 在应用的/home下 把证书cp到/usr/local/apache2/conf 2. 打开文件/usr/local/apache2/conf/extra/httpd-ssl.conf,找到 ...

  9. (.Net) NLog 记录日志功能

    https://codeload.github.com/NLog/NLog/zip/v4.6.6 https://nlog-project.org/?r=redirect Logger logger ...

  10. Nexus上传npm包

    1.创建npm仓库 私服仓库npm-hosted 代理仓库npm-proxy npm-group 创建成功 在工程的根目录下创建文件 .npmrc registry=http://xxx:8081/n ...