How to get HttpSession from sessionId in grails application

无人久伴 提交于 2019-12-10 12:14:21

问题


I have grails application, using sessionRegistry I can get sessionId.

Now, how can I get HttpSession from that sessionId.


回答1:


If you want the HttpSession then how about this:

import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
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

@Component
class SessionTracker implements HttpSessionListener, ApplicationContextAware {

    private static final ConcurrentMap<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>();

    public 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)
    }
}

Once you drop this into src/groovy it should be automatically available in your Spring context. You can use it like this after injecting into a controller or service.

sessionTracker.getSessionById('sessionId')



回答2:


Try this:

def sessions = ContextListener.instance().getSessions()
def sessionToInvalidate = sessions.find{it.id == sessionId}

Update: as Burt Beckwith mentioned, ContextListener is not standart class. However, it's easy to implement. You can see how it's implemented in App info grails plugin here



来源:https://stackoverflow.com/questions/37461557/how-to-get-httpsession-from-sessionid-in-grails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!