Groovy & Grails: Controllers and URLs
Controllers Receive HTTP
A controller delivers HTTP requests to the right code and returns a response. Each public method on a controller is an action, and Grails maps a URL to an action by convention: the controller name is the first URL segment and the action name is the second segment.
class BookController {
def index() {
render view: "list", model: [books: Book.list()]
}
def show() {
def book = Book.get(params.id)
render view: "show", model: [book: book]
}
}The params map holds everything the request carries, including query strings and form fields. A GET request to /book/show?id=7 sets params.id to 7, and the action loads the matching row.
Returning Data
Actions can render views, redirect to another URL, or respond with raw content such as JSON.
def about() {
redirect action: "index"
}
def api() {
render contentType: "application/json", text: "{"status": "ok"}"
}Redirects send the browser to another action, while render directly writes a response body. The JSON example shows how easy it is to expose an endpoint.
URL Mapping Options
The default convention is already friendly, but the UrlMappings class lets you shape URLs further or set the root route.
class UrlMappings {
static mappings = {
"/books/$id"(controller: "book", action: "show")
"/"(view: "/index")
}
}The first mapping turns /books/7 into the book controller show action with id 7. The second routes the root URL to the index view. Restful mappings can also generate actions for each CRUD verb automatically.
Following the Flow
A typical request travels browser to Grails router to controller action, which calls a service or domain class and returns a view model. Keeping controller actions thin and moving rules into services keeps the app maintainable.
Key Points
- Controllers receive requests; each public method is an action.
- params carries request data such as ids and form values.
- render outputs views, content, or JSON; redirect sends browsers elsewhere.
- UrlMappings lets you shape URLs without changing controller code.