1.编写HttpSessionListener实现类
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
MySessionContext.addSession(se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
MySessionContext.delSession(se.getSession());
}
}
2.自定义Session上下文(容器)
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;
public class MySessionContext {
private static ConcurrentHashMap<String,Object> container = new ConcurrentHashMap<>();
public static synchronized void addSession(HttpSession session){
if (session!=null){
container.put(session.getId(),session);
}
}
public static synchronized void delSession(HttpSession session){
if (session!=null){
container.remove(session.getId());
}
}
public static synchronized HttpSession getSession(String sessionId){
if (StringUtils.hasText(sessionId)){
return (HttpSession) container.get(sessionId);
}
return null;
}
}
3.配置注册监听器
@Configuration
public class ListenerConfig {
@SuppressWarnings({ "rawtypes","unchecked"})
@Bean
public ServletListenerRegistrationBean listenerRegistrationBean(){
ServletListenerRegistrationBean srb =new ServletListenerRegistrationBean();
srb.setListener(new MySessionListener());
return srb;
}
}
4.测试
@ResponseBody
@GetMapping("/get_session")
public String getSession(String sessionId){
HttpSession session;
session = MySessionContext.getSession(sessionId);
return (String) session.getAttribute("xxx");
}
@ResponseBody
@GetMapping("/test_session")
public String testCK(HttpServletRequest request) throws UnsupportedEncodingException {
request.getSession().setAttribute("xxx","hello world");
String id = request.getSession().getId();
System.out.println("id = " + id);
return id;
}