如何在grails应用程序中从sessionId获取HttpSession [英] How to get HttpSession from sessionId in grails application

查看:142
本文介绍了如何在grails应用程序中从sessionId获取HttpSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Now, how can I get HttpSession from that sessionId.

推荐答案

如果你想要 HttpSession 那么这个如何:

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

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

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

这篇关于如何在grails应用程序中从sessionId获取HttpSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆