Java 从Shiro主题获取grails域对象

Java 从Shiro主题获取grails域对象,java,grails,groovy,shiro,Java,Grails,Groovy,Shiro,我正在做一个简单的小grails应用程序,并决定使用Shiro进行注册/安全,我遇到了一个可能很愚蠢的问题 我已经生成了User和Realm类,然后对用户进行了扩展,使其与帖子有一对多的关联,即用户可以编写博客条目。但是如何从Shiro主题获取域对象呢 我尝试了以下方法: def currentUser = SecurityUtils.getSubject() def posts = Post.findByUser(currentUser) 但这给了我:消息:没有找到能够从org.apache

我正在做一个简单的小grails应用程序,并决定使用Shiro进行注册/安全,我遇到了一个可能很愚蠢的问题

我已经生成了User和Realm类,然后对用户进行了扩展,使其与帖子有一对多的关联,即用户可以编写博客条目。但是如何从Shiro主题获取域对象呢

我尝试了以下方法:

def currentUser = SecurityUtils.getSubject()
def posts = Post.findByUser(currentUser)
但这给了我:消息:没有找到能够从org.apache.shiro.web.subject.support.WebDelegatingSubject类型转换为com.lordfoom.challengetrackr.User类型的转换器

域类如下所示:

class User {
    String username
    String passwordHash

    static hasMany = [ roles: Role, permissions: String, posts: Post ]

    static constraints = {
        username(nullable: false, blank: false, unique: true)
    }
}



class Post {

    String title;
    String body; 

    static belongsTo = [user:User]
    static constraints = {
        title(nullable:false, blank: false, unique: true)
        user(unique:true)
    }
}
有没有一种简单的方法可以从Shiro主题获取当前登录用户的域对象?还是我必须查一下


非常感谢您的帮助。

如果我理解正确,您只想为当前登录的用户检索用户对象,是吗

我通常通过设置包含两个方法的UserService来实现这一点。然后我可以在整个应用程序中实现getLocalUser

import org.apache.shiro.SecurityUtils

class UserService {
    /**
     * for currently logged in user
     */
    def getLocalUserId(){
        def userName  = SecurityUtils.subject?.principal
        User.findByUsername(userName)
    }

    User getLocalUser(){
        getLocalUserId()
    }
}

希望这有帮助。

如果我理解正确,您只想为当前登录的用户检索用户对象,是吗

我通常通过设置包含两个方法的UserService来实现这一点。然后我可以在整个应用程序中实现getLocalUser

import org.apache.shiro.SecurityUtils

class UserService {
    /**
     * for currently logged in user
     */
    def getLocalUserId(){
        def userName  = SecurityUtils.subject?.principal
        User.findByUsername(userName)
    }

    User getLocalUser(){
        getLocalUserId()
    }
}

希望这能有所帮助。

谢谢,这很有意义-我想我只是希望它能以某种方式连接到主题,因为我使用插件生成了域对象-一厢情愿;谢谢,这是有道理的-我想我只是希望它以某种方式连接到主题,因为我使用插件生成域对象-一厢情愿;