Sunday, October 15, 2017

Grails - Register SessionListener as a Spring Bean

Grails - Register SessionListener as a Spring Bean

At first you have to create an listener of session as below:


package com.multidb.listener

import javax.servlet.http.HttpSessionEvent
import javax.servlet.http.HttpSessionListener
/**
 * Created by pritom on 15/10/2017.
 */
class HttpSessionServletListener implements HttpSessionListener {
    @Override
    void sessionCreated(HttpSessionEvent event) {
        println("HttpSessionServletListener:httpSessionCreated:${event.session}")
    }

    @Override
    void sessionDestroyed(HttpSessionEvent event) {
        println("HttpSessionServletListener:sessionDestroyed:${event.session}")
    }
}

Then you need to register in grails-app/conf/spring/resources.groovy as below:


import com.multidb.listener.HttpSessionServletListenererDataSource

beans = {
    httpSessionServletListener(HttpSessionServletListener) {

    }
}

And finally in Bootstrap.groovy


import com.multidb.listener.HttpSessionServletListener
import org.codehaus.groovy.grails.commons.GrailsApplication
import javax.servlet.ServletContext

class BootStrap {
    ServletContext servletContext
    GrailsApplication grailsApplication
    HttpSessionServletListener httpSessionServletListener

    def init = { servletContext ->
        servletContext.addListener(httpSessionServletListener)
    }

    def destroy = {

    }
}

So after an session is created or destroyed your custom listener will be notified.

No comments:

Post a Comment