Tuesday, 21 October 2008

Accessing Session from a Grails Service

Grails makes the session object (instance of the Servlet API's HttpSession class) directly available in the Controllers and Tag Libraries.

Furthermore, the Grails implementation of HttpSession allows you to access the session as a Groovy map.

session.user = "Robert"

will store a user name in the session's attribute list.

I wanted to encapsulate session data in a service and avoid defining session properties many places.

However, the session is not directly available in a Grails Service. So if you want to access the session from a Service, you do it via the RequestContextHolder class (part of the Spring framework).

Here is simple Service that does exactly this:

import javax.servlet.http.HttpSession
import org.springframework.web.context.request.RequestContextHolder

class SessionStorageService {

static transactional = false
static scope = "singleton"

def setUser(User user) {
getSession().user = user
}

def getUser() {
getSession().user
}

private HttpSession getSession() {
return RequestContextHolder.currentRequestAttributes().getSession()
}
}

This service is made available in Controllers by automatic dependency injection by placing a property in the controller with the name sessionStorageService:

class BaseController {
def sessionStorageService
...
sessionStorageService.setUser("Robert")
...
}
Any comments or suggestions are appreciated .

Monday, 29 September 2008

First Blog ...

Primarily a Java Developer's Blog. I will be using this to share my experience with software development technologies and as a notebook to remember ...

Keywords are: Grails, Groovy, Java, Hibernate, Spring, ActorFrame