How to work with Grails Http sessions

10,890

Solution 1

Grails uses the same servlet API as Java EE, though it provides a few extra convenience methods. Within a Grails controller, taglib or GSP there are implicit variables request and session that refer to the current HTTPServletRequest and HttpSession.

Here's an example of how Grails makes it slightly more convenient to work with these objects:

Java

Object fooAttr = session.getAttribute("foo");

Grails

def fooAttr = session["foo"]

Solution 2

you can work with the "session" object

grails session

Solution 3

After the user logs in, set the value(username) in the session. For example, your domain class is User.groovy. So in your login method in controller:, you can do:

def login()
{
    def u = new User()
    u.properties[
            'login',
            'password',
            ] = params        
    if(u.save())
    session.user = u
}

After that, whenever you want to check if the session is still on, just do

if(session.user != null)
//your code
Share:
10,890
raffian
Author by

raffian

Applications architect and code slinger since 2000, my background is full stack Java. Reach me at 72616666692e6970616440676d61696c2e636f6d My other passion is landscape photography, check it out if you're interested!

Updated on September 09, 2022

Comments

  • raffian
    raffian over 1 year

    I'm new to Grails and I'm struggling with sessions..

    In a controller, how do I check is the user has a valid session? In Java/Spring MVC, it's simple request.getSession(), so what's the convention in Grails?

    How do I add/get values from the session?

    Thanks,