how to use session in grails

19,211

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.

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.

** Edit **

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 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
       …
   }
}
Share:
19,211

Related videos on Youtube

Sumon Bappi
Author by

Sumon Bappi

Each person should have two virtue in life. One # Patience && Two # Gratefulness

Updated on June 04, 2022

Comments

  • Sumon Bappi
    Sumon Bappi almost 2 years

    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')
        }
    
    }
    
  • Sumon Bappi
    Sumon Bappi almost 11 years
    thanks for your reply. I am already using spring security core plugin. But I don't know how to use session from it. I am giving a sample source code in the editor. It redirect to login page if condition false. but does not redirect createUser page if true. Can you help now ?!
  • osborp
    osborp almost 11 years
    I'm not sure I completely understand the problem - why do you need to use the session directly? I've updated my answer with some code snippets. Hope it helps.
  • Sumon Bappi
    Sumon Bappi almost 11 years
    thanks @osborp it helps for now. I will work on details of session later. But right now this is the answer for the basic
  • Tung
    Tung over 7 years
    Thanks for reply. It helps me!