Controllers Scopes
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 javax.servlet.HttpSession
- request - The request object allows the storage of objects for the current request only. The request object is an instance of javax.servlet.HttpServletRequest
- flash - See below.
Accessing the request parameters, session etc
Every controller has a number of properties injected into them at runtime, these make it possible to access the request, session etc. For a full reference on these please see the
Dynamic Methods Reference
class BookController {
def find = {
def findBy = params["findBy"]
def appContext = servletContext["appContext"]
def loggedUser = session["logged_user"] // do stuff
// return model
return model
};
}Using Flash Scope
Flash scope is a concept introduced by Rails. It 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
}