Can I inject a service into a filter in Grails?

后端 未结 3 1220
不思量自难忘°
不思量自难忘° 2021-02-14 15:32

I have a service to get and set the user in the session. I would like to pass in some user information to each view if there is a logged in user and thought a filter would be th

3条回答
  •  时光取名叫无心
    2021-02-14 16:20

    import org.codehaus.groovy.grails.web.context.ServletContextHolder
    import org.springframework.context.ApplicationContext
    import org.springframework.web.context.support.WebApplicationContextUtils
    class SecurityFilters {
        def userService
    
        def filters = {
            setUser(controller:'*', action:'*') {
                before = {
                    def servletCtx = ServletContextHolder.getServletContext()
                    ApplicationContext applicationContext = WebApplicationContextUtils.
                        getRequiredWebApplicationContext(servletCtx)
                    userService =applicationContext.getBean('userService')
                    if (userService.isLoggedIn()) {
                        request.user = userService.getUser()
                    } else {
                        request.user = null
                    }
                }
            }
        }   
    }
    

提交回复
热议问题