将登录用户添加到所有GSP页面的上下文中 [英] Add logged in user to context for all GSP pages
问题描述
我希望始终可以访问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.htmlI 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屋!