如何在grails中使用会话 [英] how to use session in grails

查看:68
本文介绍了如何在grails中使用会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的grails.我必须参加会议.我看过会议文件.但是不知道将代码放在我的控制器中的什么位置.我有一个用于学生创建名称createStudent的页面.现在,我希望该页面仅在用户处于会话状态时才可以访问.现在我该怎么办.登录时我是否必须在变量中设置用户.有人可以帮我吗?

I am new to grails. And I have to work with session. I have seen the session documentation. But no idea where to put the code in my controller. I have a page for student creation names createStudent. Now I want that this page only be access able when the user will be in session. Now how can I do it. Should I have to set the user in a variable at the time of login. Can anyone please help me on this ?

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)方法.另外,有些插件,例如 Spring Security Core插件已经很好地解决了这个问题.

You could use the session.getAttribute(key) and session.setAttribute(key, value) methods inside your controller. Alternatively, there are plugins such as the Spring Security Core Plugin that already handle this very well.

Peter Ledbrook为Spring Security插件此处和插件文档链接到至少另一本教程.

There's a good tutorial by Peter Ledbrook for the Spring Security plugin here and the plugin documentation links to at least one other tutorial.

**编辑**

如您所建议,为了直接使用会话,需要在会话中更早地设置用户.例如:

As you suggested, in order to use the session directly the user would need to be set in the session at an earlier point. For example:

def setCurrentStudent() {
    def aStudent = [name: "Student1"]
    session["user"] = aStudent
    render "Added $aStudent to the session."
}

Spring Security将在登录时自动执行此操作.然后,可以使用springSecurityService随时访问当前用户.

Spring Security will do this automatically at login. Then, the current user can then be accessed at any time using the springSecurityService.

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

这篇关于如何在grails中使用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆