将登录用户添加到所有GSP页面的上下文中 [英] Add logged in user to context for all GSP pages

查看:141
本文介绍了将登录用户添加到所有GSP页面的上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望始终可以访问grails中的当前用户域实例。我目前使用弹簧安全。我如何着手将当前用户添加到所有GSP页面的上下文中?我使用的是request.user,但那并不总是填充。



例如,我希望能够始终访问

  $ {_ currentUser.messages} 

我知道UserDetails服务,但这是针对静态数据的。

解决方案

使用过滤器,将其添加到grails-app / conf中:

  package my.project 
$ b $ class UserFilters {

def springSecurityService

//将用户添加到params对象总是
def filters = {
addUser(controller:'*',action:'*'){
before = {
params.myAddedUser = springSecurityService.currentUser
}
}
}

//将用户添加到模型(如果已定义)
之后= {地图模型 - >如果(参数&&;& params ['myAddedUser'])model.myAddedUser = params.myAddedUser $ b $($!
$ b if(!model)model = [:]

if b}

}

然后您将可以在所有视图/控制器。在视图中,如果模型是在控制器(任何模型)中定义的,并且在控制器中它将通过params对象来访问,则它们将通过参数或模型来访问。

意识到它也将应用于图像。因此,使用文档将过滤器应用到您需要的内容 http:// grails .org / doc / 2.2.1 / ref / Plug-ins / filters.html

I want to always have access to the current user domain instance in grails. I am currently using spring security. How do I go about adding current user to the context for all GSP pages? I was using request.user but thats not always populated.

For instance I want to be able to always access

${_currentUser.messages}

I know about the UserDetails service, but that is for static data. I am going to be accessing things that could be changing.

解决方案

Use filters, add to grails-app/conf:

package my.project

class UserFilters {

    def springSecurityService

    // add user to params object always
    def filters = {
        addUser(controller: '*', action: '*') {
            before = {
                params.myAddedUser = springSecurityService.currentUser
            }
        }
    }

    // add user to model if it is defined
    after = { Map model ->

        if(!model) model = [:]

        if ( params && params['myAddedUser']) model.myAddedUser = params.myAddedUser
    }

}

Then you will be able to retrieve it in all view/controllers. In views they will be accessible either through params or through model if model was defined in controller(any model) and in controllers it will be accessed through params object.

But be aware as it will be applied to images also. So use docs to apply filters to what you need http://grails.org/doc/2.2.1/ref/Plug-ins/filters.html

这篇关于将登录用户添加到所有GSP页面的上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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