Grails通过sessionId获取session对象
Grails通过sessionId获取session对象
思路:自定义一个类用来监听session
,所有session
存入map
中,sessionId
作为读取的key
创建监听类 SessionTracker
package com.session import org.springframework.beans.BeansException import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.web.context.WebApplicationContext import javax.servlet.http.HttpSession import javax.servlet.http.HttpSessionEvent import javax.servlet.http.HttpSessionListener import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap class SessionTracker implements HttpSessionListener, ApplicationContextAware { private static final ConcurrentMap<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>(); void setApplicationContext(ApplicationContext applicationContext) throws BeansException { def servletContext = ((WebApplicationContext) applicationContext).getServletContext() servletContext.addListener(this); } void sessionCreated(HttpSessionEvent httpSessionEvent) { sessions.putAt(httpSessionEvent.session.id, httpSessionEvent.session) } void sessionDestroyed(HttpSessionEvent httpSessionEvent) { sessions.remove(httpSessionEvent.session.id) } HttpSession getSessionById(id) { sessions.get(id) } }
在 grails-app/conf/resources.groovy
中注册
import com.session.SessionTracker // Place your Spring DSL code here beans = { // 自定义session监听器 sessionTracker(SessionTracker) }
获取session
package com.genee import org.springframework.web.context.request.RequestContextHolder import javax.servlet.http.HttpSession class HiController { // 注入监听对象 def sessionTracker def index() { // 获取session def sessionId = RequestContextHolder.currentRequestAttributes().getSessionId() println "原sessionId:$sessionId" // 根据sessionId获取session对象 HttpSession httpSession = sessionTracker.getSessionById(sessionId).getId() println "获取到session后:"+httpSession.getId() // 使session立即失效 sessionTracker.getSessionById(sessionId).invalidate() render sessionId } }
相关推荐
houmenghu 2020-11-17
思君夜未眠 2020-08-25
阳光之吻 2020-08-03
mbcsdn 2020-06-05
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
取个好名字真难 2020-08-06
歆萌 2020-08-03
婷婷小屋 2020-07-28
solarspot 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06