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 .
11 comments:
Appart from the undefined method RequestAttributes.getSession()?
The Grails implementation of RequestAttributes inherits the getSession() method from Spring's ServletWebRequest. Note casting is not necessary since Grails is dynamically loading the methods.
Sometime I need to use some available variable in Controller such as "request", "response", "session", etc. I don't know how to get these variables but I always define a method called initService, its params can be the request or session itself. Everytime I use my service, I call this method and everything is ok! Is it right?
Thank you, the RequestContextHolder
worked from the src/groovy subdirectory.
Thanks, very helpful posting
Thank you very nice posting... web application
You should avoid using "id" as name of property stored in the session object as it probably is reserved for internal used by Grails.
Thanks, very helpful.
Why not use a GrailsWebRequest?
http://grails.org/doc/1.0.x/api/org/codehaus/groovy/grails/web/servlet/mvc/GrailsWebRequest.html
But the Session object we get from this doesn't contain 'attribute HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY'.
I actually want to get the loggedIn user details in src/groovy classes.
And SpringSecurityUtils.getSecurityContext(session) returns me null.
P.S. I have checked the HTTPSession Object, It contains all other attributes.
Post a Comment