-->

How to get HttpSession from sessionId in grails ap

2019-06-13 08:03发布

问题:

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