Available Scopes
Scopes are essentially hash like objects that allow you to store variables. The following scopes are available to controllers:
- servletContext - Also known as application scope, this scope allows you to share state across the entire web application. The servletContext is an instance of javax.servlet.ServletContext
- session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession
- request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest
- params - Mutable map of incoming request (CGI) parameters
- flash - See below.
Accessing Scopes
Scopes can be accessed using the variable names above in combination with Groovy's array index operator even on classes provided by the Servlet API such as the
HttpServletRequest:
class BookController {
def find = {
def findBy = params["findBy"]
def appContext = request["foo"]
def loggedUser = session["logged_user"] }
}
You can even access values within scopes using the de-reference operator making the syntax even clearer:
class BookController {
def find = {
def findBy = params.findBy
def appContext = request.foo
def loggedUser = session.logged_user }
}
This is one of the ways that Grails unifies access to the different scopes.
Using Flash Scope
Grails supports the concept of
flash scope is a temporary store for attributes which need to be available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirection, for example:
def delete = {
def b = Book.get( params.id )
if(!b) {
flash.message = "User not found for id ${params.id}"
redirect(action:list)
}
… // remaining code
}