Redirects
Actions can be redirected using the
redirect method present in all controllers:
class OverviewController {
def login = {} def find = {
if(!session.user)
redirect(action:login)
…
}
}
Internally the
redirect method uses the
HttpServletResonse object's
sendRedirect
method.
The
redirect
method expects either:
- Another closure within the same controller class:
// Call the login action within the same class
redirect(action:login)
- The name of a controller and action:
// Also redirects to the index action in the home controller
redirect(controller:'home',action:'index')
- A URI for a resource relative the application context path:
// Redirect to an explicit URI
redirect(uri:"/login.html")
// Redirect to a URL
redirect(url:"http://grails.org")
Parameters can be optionally passed from one action to the next using the
params
argument of the method:
redirect(action:myaction, params:[myparam:"myvalue"])
These parameters are made available through the
params dynamic property that also accesses request parameters. If a parameter is specified with the same name as a request parameter the request parameter is overridden and the controller parameter used.
Since the
params
object is also a map, you can use it to pass the current request parameters from one action to the next:
redirect(action:"next", params:params)
Finally, you can also include a fragment in the target URI:
redirect(controller: "test", action: "show", fragment: "profile")
will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".
h4. Chaining
Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the
first
action in the below action:
class ExampleChainController {
def first = {
chain(action:second,model:[one:1])
}
def second = {
chain(action:third,model:[two:2])
}
def third = {
[three:3])
}
}
Results in the model:
The model can be accessed in subsequent controller actions in the chain via the
chainModel
map. This dynamic property only exists in actions following the call to the
chain
method:
class ChainController { def nextInChain = {
def model = chainModel.myModel
…
}
}
Like the
redirect
method you can also pass parameters to the
chain
method:
chain(action:"action1", model:[one:1], params:[myparam:"param1"])