【问题标题】:How to get HttpSession from sessionId in grails application如何从 grails 应用程序中的 sessionId 获取 HttpSession
【发布时间】:2016-09-24 11:59:09
【问题描述】:

我有 grails 应用程序,使用 sessionRegistry 我可以获得 sessionId。

现在,我如何从该 sessionId 中获取 HttpSession。

【问题讨论】:

  • “sessionFactory”是指Hibernate SessionFactory?这与 HTTP 会话无关,只是巧合地相似。 “会话”概念用于各种地方,例如JMS 等。它们不相关且不共享 ID。

标签: grails spring-security sessionid httpsession


【解决方案1】:

如果你想要HttpSession 那么这个怎么样:

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

一旦你把它放到 src/groovy 中,它应该会自动在你的 Spring 上下文中可用。注入控制器或服务后,您可以像这样使用它。

sessionTracker.getSessionById('sessionId')

【讨论】:

    【解决方案2】:

    试试这个:

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

    更新: 正如 Burt Beckwith 提到的,ContextListener 不是标准类。但是,它很容易实现。您可以在 App info grails plugin here

    中查看它是如何实现的

    【讨论】:

    • ContextListener 不是标准类,它必须是您在 web.xml 中注册为监听器以跟踪会话的应用程序中使用的东西。没有那个类源,这个答案根本没有用。
    猜你喜欢
    • 2010-11-18
    • 2012-08-12
    • 2011-03-21
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2013-05-30
    • 2012-04-06
    • 2013-10-29
    相关资源
    最近更新 更多