Java Reference
In-Depth Information
As illustrated in Listing 7-13, the controller, when invoked with a request to
/hello/index
, will execute
an
index()
action defined in the controller, and the
index()
action will render a textual response,
using the
render()
method. The full URL to invoke the
index()
action in the
HelloController
is
http://localhost:8080/chapter5/hello/index
. As shown in the listing, there can be any number of
actions in a controller.
If you specify the view name in the
render()
method, as shown in Listing 7-14, Grails assumes you
mean a view at the location
grails-app/views/hello/hello.gsp
and renders a view called
hello
.
Listing 7-14. Rendering a View
class HelloController {
...
def show() {
render view: "hello"
}
...
}
Calling the redirect( ) Method
The second option to exit a controller action is to call the
redirect( )
method to issue an HTTP
redirect to another URL. Grails provides all controllers with a
redirect( )
method that accepts a
Map as an argument. The Map should contain all the information that Grails needs to carry out the
redirect, including the name of the action to redirect to.
In addition, the Map can contain the name of the controller to redirect to. Listing 7-15 shows a
standard redirect from the first action to the second action within the same controller.
Listing 7-15. Redirecting to an Action in the Same Controller
class HelloController {
def first() {
redirect action: "second"
}
def second() {
...
}
}
If the redirect is for an action in another controller, you must specify the name of the other controller.
Listing 7-16 demonstrates how to redirect to an action in another controller.
Listing 7-16. Redirecting to an Action in Another Controller
class HelloController {
def first() {
redirect action: "second", controller: "other"
}
}
In Listing 7-16, the
first()
action in
HelloController
redirects to the
second()
action in the
Other
Controller.