SpringBoot之Session新增、删除、获取配置与使用
文章目录
- SpringBoot之Session新增、删除、获取配置与使用
- 1. SpringBoot版本
- 2. 定义增删查Session的类
- 3. 定义Session的监听器
- 4. 使用
自定义根据
sessionId
进行session
的新增、删除、获取操作
1. SpringBoot版本
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.5.RELEASE</version></parent>
2. 定义增删查Session的类
package com.yuan.webframework.config;import javax.servlet.http.HttpSession;
import java.util.HashMap;/*** @author: jinshengyuan* @date: 2020-03-12* desceptions: 自定义根据sessionId进session的新增、删除、获取操作*/
public class MySessionContext {private static MySessionContext instance;private final HashMap<String, HttpSession> sessionMap;private MySessionContext() {sessionMap = new HashMap<>();}/*** 实例化对象* @return*/public static MySessionContext getInstance() {if (instance == null) {instance = new MySessionContext();}return instance;}/*** 添加session* @param session*/public synchronized void addSession(HttpSession session) {if (session != null) {sessionMap.put(session.getId(), session);}}/*** 删除session* @param session*/public synchronized void deleteSession(HttpSession session) {if (session != null) {sessionMap.remove(session.getId());}}/*** 获取session* @param sessionId* @return*/public synchronized HttpSession getSession(String sessionId) {if (sessionId == null) {return null;}return sessionMap.get(sessionId);}
}
3. 定义Session的监听器
package com.yuan.webframework.config;import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;/*** @author: jinshengyuan* @date: 2020-03-12* @desceptions: 自定义新增、删除session的监听器*/
@WebListener
public class MySessionListener implements HttpSessionListener {private final MySessionContext sessionContext = MySessionContext.getInstance();@Overridepublic void sessionCreated(HttpSessionEvent se) {//System.out.println("session被创建了哦");//HttpSession session = se.getSession();//sessionContext.addSession(session);}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {//System.out.println("session失效了哦");HttpSession session = se.getSession();sessionContext.deleteSession(session);}
}
4. 使用
/*** 通过sessionId获取HttpSession对象** @param sessionId* @return*/public final static HttpSession getSessionById(String sessionId) {return MySessionContext.getInstance().getSession(sessionId);}