【问题标题】:current sessions in GrailsGrails 中的当前会话
【发布时间】:2012-03-15 22:52:32
【问题描述】:

我是 Grails 2.0 框架的初学者,我正在努力学习本教程 http://grails.org/Simple+Avatar+Uploader。我实现了这段代码,但我在 UserController.groovy 的这一行中遇到错误 'def user = User.current(session)' as 'No such property: User for class: grailtwitter.PersonController' 我假设这一行采用用户的当前会话。我正在寻找有关其工作原理的解释?

【问题讨论】:

    标签: grails


    【解决方案1】:

    此代码不完整。控制器假定您有一种方法可以识别当前登录的用户。隐含的def user = User.current(session) 行假定您已经在用户类本身上定义了current() 方法,该方法接受会话并可能使用您在其中设置的某些字段来检索用户。那会有点愚蠢。

    执行此操作的常用方法是构建您自己的身份验证机制。请注意,这是一种幼稚的做法,使用Spring Security Core好得多,除非您想让您的应用程序保持打开状态,以防止巨大的安全漏洞。但是,为了练习,类似:

    def login = {
        //if you're stupid enough to store your passwords in plain text and not sanitize user inputs, you deserve to be hacked
        def user = User.findByPassword(params.password) 
        if(user){
           session.user = user
        }
    }
    

    然后您可以将教程中的违规行 (--def user = User.current(session)--) 替换为

    def user = session.user ?: new User(userid:"I'm a little teapot") 
    

    在您走得更远之前,您可能想在走得更远之前先浏览一下free eBook on Grails。也强烈推荐Grails in Action

    【讨论】:

      【解决方案2】:

      当我过去遇到这种情况时,这是因为我没有导入类,而 Grails/Groovy 认为我正在尝试访问名为 User 的变量而不是类上的方法。

      【讨论】:

      • “当前(会话)”持有什么样的数据?
      • User 类在什么包中?如果它不在 grailtwitter 包中,则需要导入。
      • 好吧..我导入了包。现在我收到不同的错误,如下“没有方法签名:org.grails.twitter.User.current() 适用于参数类型:(org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession) 值: 【会话内容:org.codehaus.groovy.grails.FLASH_SCOPE = org.codehaus…………”
      • 我认为您忽略了对// or however you select the current user 的那行代码的注释。换句话说,您可能无法复制和粘贴该代码并期望它能够工作。您需要其他方式来获取用户。
      猜你喜欢
      • 2013-05-18
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多