Grails通過sessionId獲取session物件

Genee發表於2019-02-22

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
    }
}
複製程式碼

相關文章