如何在 GSP 中使用 Spring Security Grails 插件获取 current_user [英] How to get current_user by using Spring Security Grails plugin in GSP
问题描述
我是 Grails 的新手.我正在使用 Spring Security Grails 插件 进行身份验证.我想在我的视图 gsp 文件中获取当前用户.
I am newbie in Grails. I am using Spring Security Grails plugin for Authentication purpose. I want to get current user in my view gsp file.
我正在尝试这样......
I am trying like this ...
<g:if test="${post.author == Person.get(springSecurityService.principal.id).id }">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
在这里,我想显示编辑此帖子链接,仅指向由登录用户创建的帖子.但它显示错误 -
Here I want to show Edit this post link to only those posts who created by signed_in user. But It showing ERROR -
Error 500: Internal Server Error
URI
/groovypublish/post/list
Class
java.lang.NullPointerException
Message
Cannot get property 'principal' on null object
这是我的 Post.groovy --
Here is my Post.groovy --
class Post {
static hasMany = [comments:Comment]
String title
String teaser
String content
Date lastUpdated
Boolean published = false
SortedSet comments
Person author
....... more code ....
这是我的 Person.groovy 域类文件 --
Here is my Person.groovy Domain Class File --
class Person {
transient springSecurityService
String realName
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
byte[] avatar
String avatarType
static hasMany = [followed:Person, posts:Post]
static searchable = [only: 'realName']
........ more code ......
请帮忙.
推荐答案
试试springSecurity插件提供的标签,比如:
Try tags provided by springSecurity plugin, something like:
<sec:isLoggedIn>
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</sec:isLoggedIn>
实际上你是想在你的 GSP 页面上注入一个服务,你可以在页面上使用一些 import 语句来完成,但我会说这不是一个好的编程习惯,我认为你应该发送当前登录用户的实例从控制器到 GSP 页面,然后对其进行检查:
Actually you are trying to inject a service on your GSP page, you can do it with some import statement on the page, but I would say it will not be good programming practice, I think you should send current logged In user's instance from the controller to the GSP page, and then perform a check on it:
假设你有控制器方法:
def showPostPage(){
Person currentLoggedInUser = springSecurityService.getCurrentUser();
[currentLoggedInUser:currentLoggedInUser]
}
并在您的 GSP 页面上:
and on your GSP page:
<g:if test="${post.author == currentLoggedInUser }">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
这篇关于如何在 GSP 中使用 Spring Security Grails 插件获取 current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!