Creating a controller
Controllers can be created with the
create-controller target. For example try running the following command from the root of a Grails project:
grails create-controller book
The command will result in the creation of a controller at the location
grails-app/controllers/BookController.groovy
:
class BookController { … }
BookController
by default maps to the /book URI (relative to your application root).
The create-controller
command is merely for convenience and you can just as easily create controllers using your favorite text editor or IDE
Creating Actions
A controller can have multiple properties that are each assigned a block of code. Each of these properties maps to a URI:
class BookController {
def list = { // do controller logic
// create model return model
}
}
This example maps to the
/book/list
URI by default thanks to the property being named
list
.
The Default Action
A controller has the concept of a default URI that maps to the root URI of the controller. By default the default URI in this case is
/book
. The default URI is dictated by the following rules:
- If only one action is present the default URI for a controller maps to that action.
- If you define an
index
action which is the action that handles requests when no action is specified in the URI /book
- Alternatively you can set it explicitly with the
defaultAction
property:
static defaultAction = "list"