Session 如何在grails中使用会话

Session 如何在grails中使用会话,session,grails,grails-2.0,grails-controller,Session,Grails,Grails 2.0,Grails Controller,我不熟悉grails。我必须和session一起工作。我看过会议文件。但我不知道把代码放在我的控制器里。我有一个学生创建名称的页面。现在我希望只有当用户在会话中时才能访问此页面。现在我该怎么做呢。我应该在登录时在变量中设置用户。有人能帮我吗 def index() { def user = session["user"] if (user){ redirect(controller: 'admistratorAction', action: 'createUser

我不熟悉grails。我必须和session一起工作。我看过会议文件。但我不知道把代码放在我的控制器里。我有一个学生创建名称的页面。现在我希望只有当用户在会话中时才能访问此页面。现在我该怎么做呢。我应该在登录时在变量中设置用户。有人能帮我吗

def index() {
    def user = session["user"]
    if (user){
        redirect(controller: 'admistratorAction', action: 'createUser')
    }else{
        redirect(controller: 'login', action: 'index')
    }

}

您可以在控制器中使用
session.getAttribute(key)
session.setAttribute(key,value)
方法。或者,有一些插件,例如,已经很好地处理了这个问题

彼得·莱德布鲁克(Peter Ledbrook)为Spring安全插件提供了一个很好的教程,插件文档链接到至少一个其他教程

**编辑**

正如您所建议的,为了直接使用会话,需要在会话中的较早时间点设置用户。例如:

def setCurrentStudent() {
    def aStudent = [name: "Student1"]
    session["user"] = aStudent
    render "Added $aStudent to the session."
}
Spring Security将在登录时自动执行此操作。然后,可以随时使用springSecurityService访问当前用户

class SomeController {
   def springSecurityService
   def someAction = {
       def user = springSecurityService.currentUser
       …
   }
}

谢谢你的回复。我已经在使用spring安全核心插件了。但我不知道如何使用它的会话。我在编辑器中提供了一个示例源代码。如果条件为false,它将重定向到登录页面。但如果为true,则不会重定向createUser页面。你现在能帮忙吗?!我不确定我是否完全理解这个问题-为什么需要直接使用会话?我已经用一些代码片段更新了我的答案。希望能有帮助。谢谢@osborp,现在有帮助了。我将在稍后讨论会议的细节。但现在,这是回答基本问题的答案。这对我有帮助!