SpringSecurity根据sessionid获取用户信息
1.定义一个对象存储session
package com.rexyn.bridge.listener;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
public class MySessionContext {
private static MySessionContext instance;
private HashMap<String, HttpSession> sessionMap;
private MySessionContext() {
sessionMap = new HashMap<String,HttpSession>();
}
public static MySessionContext getInstance() {
if (instance == null) {
instance = new MySessionContext();
}
return instance;
}
public synchronized void addSession(HttpSession session) {
if (session != null) {
sessionMap.put(session.getId(), session);
}
}
public synchronized void delSession(HttpSession session) {
if (session != null) {
sessionMap.remove(session.getId());
}
}
public synchronized HttpSession getSession(String sessionID) {
if (sessionID == null) {
return null;
}
return sessionMap.get(sessionID);
}
}
2.监听器监听session
package com.rexyn.bridge.listener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionListener {
private MySessionContext myc = MySessionContext.getInstance();
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.addSession(session);
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.delSession(session);
}
}
3.web.xml配置监听器
<listener>
<listener-class>com.rexyn.bridge.listener.SessionListener</listener-class>
</listener>
4.根据sessionid解析用户信息
/**
*
* @Author fushaokai
* @Description //TODO 根据请求头中的token获取用户登录心心
* @Param
* @Return
**/
public Member getCurrentMemberByHeaderToken(String token){
MySessionContext myc= MySessionContext.getInstance();
HttpSession sess = myc.getSession(token);
try {
SecurityContext context_session = (SecurityContext) sess.getAttribute("SPRING_SECURITY_CONTEXT");
Authentication tokenentication = context_session.getAuthentication();
String username = "";
if (tokenentication != null && tokenentication.getPrincipal() != null) {
username = tokenentication.getName();
return memberService.findUserByUsername(username);
}else{
throw new RuntimeException("请先登录");
}
}catch (Exception e){
throw new RuntimeException("请先登录");
}
}