user3387291
user3387291

Reputation: 151

Session variables not working in Grails

I try create new session in one controller and set variable and get this variable from session to another action. but session return null value. I use Grails 2.3.7.

class AuthorizationController {

    def signIn = {

       def session = request.getSession(true)
       session.setAttribute('username', 'zzzz')
       println(session.getAttribute('username')) // <-- here work
       redirect(action: logout)
    }

    def logout = {
        println(session.getAttribute('username')) // <-- here not work
    }
}

Upvotes: 2

Views: 1352

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

Change your code as:

class AuthorizationController {

    def signIn() {
       session.username = 'zzzz'
       println(session.username)
       redirect(action: 'logout')
    }

    def logout() {
        println(session.username)
    }
}

You don't have to create a new session, you can directly use session variable available to controllers. Also you don't have to use getters & setters to get & set values on session. You can directly use them as I've mentioned in above code.

If you are using grails > 2.x, avoid using closures in defining controller actions. Use plain method type instead.

Upvotes: 2

Related Questions