概括:
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监听器
- 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);
- }
- }
开始测试吧