springboot使用HttpSessionListener 监听器统计当前在线人数
概括:
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 监听器统计当前在线人数,拿来即用,不忽悠
原理就是很简单,就是利用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使用HttpSessionListener 监听器统计当前在线人数的更多相关文章
- Servlet监听器统计网站在线人数
本节我们利用 Servlet 监听器接口,完成一个统计网站在线人数的案例.当一个用户登录后,显示欢迎信息,同时显示出当前在线人数和用户名单.当用户退出登录或 Session 过期时,从在线用户名单中删 ...
- Servlet监听器统计在线人数
监听器的作用是监听Web容器的有效事件,它由Servlet容器管理,利用Listener接口监听某个执行程序,并根据该程序的需求做出适应的响应. 例1 应用Servlet监听器统计在线人数. (1)创 ...
- 监听器的配置,绑定HttpSessionListener监听器的使用
监听器的配置,绑定 <listener> <listener-class>监听器的全路径</listener-class> </listener> Se ...
- java-web项目:用servlet监听器实现显示在线人数
1.创建一个监听器 package com.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpS ...
- 用HttpSessionListener与HttpSessionBindingListener实现在线人数统计
在线人数统计方面的实现,最初我的想法是,管理session,如果session销毁了就减少,如果登陆用户了就新增一个,但是如果是用户非法退出,如:未注销,关闭浏览器等,这个用户的session是管理不 ...
- [转]用HttpSessionListener与HttpSessionBindingListener实现在线人数统计
原文链接:http://www.cnblogs.com/shencheng/archive/2011/01/07/1930227.html 下午比较闲(其实今天都很闲),想了一下在线人数统计方面的实现 ...
- javaEE之--------统计站点在线人数,安全登录等(观察者设计模式)
整体介绍下: 监听器:监听器-就是一个实现待定接口的普通Java程序,此程序专门用于监听别一个类的方法调用.都是使用观察者设计模式. 小弟刚接触这个,做了些简单的介绍.大神请绕道,技术仅仅是一点点, ...
- java监听器之实现在线人数显示
在码农的世界里只有bug才能让人成长,The more bugs you encounter, the more efficient you will be! java中的监听器分为三种:Servle ...
- 使用session的监听器获取当前在线人数
1首先在web.xml中配置Session的监听器 2创建监听器并且继承HttpSessionListener 3.在jsp中导入监听器 4.获取当前在线人数 5.配置到公共网络(使用natapp的免 ...
随机推荐
- itext7 html转pdf实现
公司最近做一个交易所项目,里面涉及一个需求就是将html模板,在填充数据后转换为pdf,这样防止数据更改,下面是具体实现 1 pom文件 <dependency> <groupId& ...
- java复制对象之深拷背
在java开发中,有时我们需要复制对象,并且确保修改复制得到的对象不会影响原来的对象. 于是,有些人可能会写出类似以下的代码: public class CloneTest { public stat ...
- quartz 1.6.2之前的版本,定时任务自动停掉问题
https://searchcode.com/codesearch/view/28831622/ Quartz 1.6.2 Release Notes This release contains a ...
- AES采用CBC模式128bit加密工具类
写在前面 安全测试ECB模式过于简单需要改为CBC模式加密以下为工具类及测试 AESUtils.java package com.sgcc.mobile.utils; import sun.misc. ...
- fluid.io.load_inference_model 载入多个模型的时候会报错 -- [paddlepaddle]
将多个模型部署到同一个服务时,会出现stack错误. 原因是program为全局. 改成这样,可以解决. solved by myself. for those who need it:use a n ...
- opencv马赛克python实现
最近要实现opencv视频打马赛克,在网上找了一下基本是C++的实现,好在原理一样,下面给出python实现. 原理和注意点,我都写在注释里了 import cv2 ##马赛克 def do_mosa ...
- sql server 利用存储过程http请求调用URL链接访问方法
sp_configure ; GO RECONFIGURE; GO sp_configure ; GO RECONFIGURE; GO EXEC sp_configure 'Ole Automatio ...
- wms证书配置操作
1. 在应用的/home下 把证书cp到/usr/local/apache2/conf 2. 打开文件/usr/local/apache2/conf/extra/httpd-ssl.conf,找到 ...
- (.Net) NLog 记录日志功能
https://codeload.github.com/NLog/NLog/zip/v4.6.6 https://nlog-project.org/?r=redirect Logger logger ...
- Nexus上传npm包
1.创建npm仓库 私服仓库npm-hosted 代理仓库npm-proxy npm-group 创建成功 在工程的根目录下创建文件 .npmrc registry=http://xxx:8081/n ...