Accessing Session Map in the Domain or Service Layer

16 / Jul / 2009 by Vivek Krishna 4 comments

The Session Map is available in Grails in the Views, TagLibs and the Controllers. That is, it can be directly accessed by the name “session”. If the Session Map is required to be accessed in the Service Layer or the Domain layer, such a straightforward approach will not work. In this case, a class which is a part of the Spring Framework can be used which gives the current context, the request attributes and the session. This class along with HttpSession have to be imported by issuing the following statements.

import org.springframework.web.context.request.RequestContextHolder

Now, the session variable can be defined in the Service class or Domain method as:

def session = RequestContextHolder.currentRequestAttributes().getSession()

The session attributes can now be accessed as

session.attribute

Hope this helps.

S Vivek Krishna

vivek@IntelliGrape.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Vivek Krishna

    Hi Ashish,

    Glad to know that the post helped. 🙂

    This is just one of the workarounds. It is not ideal to be accessing session information inside the service as it binds the service to the Web layer very tightly, which means, the service is “servicing” HttpRequests only.
    If that constraint is not a problem for the application, then there is no harm in using this technique.

    @ Shashi : Glad to know that this helped. 🙂

    Reply
  2. Ashish

    Thanks a lot for posting this wonderful article.
    Wonder why such criticla information are not readily available on the official site or by the authors/creators etc.

    One has to struggle to unearth such critical details.

    Thanks again Vivek

    Ashish

    Reply
  3. Shashi

    thanks for the nice article.
    It saved me a lot of work of passing the whole session object to service classes from controllers.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *