Fre*_*ded 5 grails spring-security gsp grails-2.0
我是Grails的新手.我使用Spring Security Grails插件进行身份验证.我想在我的视图gsp文件中获取当前用户.
我这样想...
<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>
Run Code Online (Sandbox Code Playgroud)
在这里,我想显示编辑此帖子链接,仅显示由signed_in用户创建的帖子.但它显示出错误 -
Error 500: Internal Server Error
URI
/groovypublish/post/list
Class
java.lang.NullPointerException
Message
Cannot get property 'principal' on null object
Run Code Online (Sandbox Code Playgroud)
这是我的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 ....
Run Code Online (Sandbox Code Playgroud)
这是我的Person.groovy域类文件 -
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 ......
Run Code Online (Sandbox Code Playgroud)
请帮忙.
iku*_*men 14
您可以使用Spring Security Taglib.对于您要执行的操作,请检查登录用户是否为发布所有者,您可以执行以下操作:
<sec:isLoggedIn>
<g:if test="${post.author.id == sec.loggedInUserInfo(field: 'id')}">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
</sec:isLoggedIn>
Run Code Online (Sandbox Code Playgroud)
如果您发现需要进行大量检查,我建议将其放入自定义taglib中
class AuthTagLib {
def springSecurityService
def isOwner = { attrs, body ->
def loggedInUser = springSecurityService.currentUser
def owner = attrs?.owner
if(loggedInUser?.id == owner?.id) {
out << body()
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它
<g:isOwner owner="${post?.author}">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:isOwner>
Run Code Online (Sandbox Code Playgroud)
尝试使用springSecurity插件提供的标签,例如:
<sec:isLoggedIn>
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</sec:isLoggedIn>
Run Code Online (Sandbox Code Playgroud)
实际上你正试图在你的GSP页面上注入一个服务,你可以在页面上用一些import语句来做,但我会说它不是很好的编程习惯,我认为你应该从控制器发送当前登录用户的实例到GSP页面,然后执行检查:
假设你有控制器方法:
def showPostPage(){
Person currentLoggedInUser = springSecurityService.getCurrentUser();
[currentLoggedInUser:currentLoggedInUser]
}
Run Code Online (Sandbox Code Playgroud)
并在您的GSP页面上:
<g:if test="${post.author == currentLoggedInUser }">
<g:link controller="post" action="edit" id="${post.id}">
Edit this post
</g:link>
</g:if>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16203 次 |
最近记录: |