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 .