Controllers and Actions

Site Admin · 11 Sep 2026 · 6 views

Understanding Controllers

Controllers in Grails handle incoming HTTP requests and produce responses. Each controller contains actions - public methods that correspond to URL endpoints. Grails maps these actions automatically based on naming conventions.

Defining Actions

class BookController {
    def index() {
        redirect(action: "list")
    }

    def list() {
        def books = Book.list()
        [books: books]
    }

    def show(Long id) {
        def book = Book.get(id)
        if (!book) {
            flash.message = "Book not found"
            redirect(action: "list")
            return
        }
        [book: book]
    }
}

Notice how parameters like id are automatically bound from the request. Grails handles parameter binding without any manual parsing.

Flash Scope

The flash scope carries messages across a single redirect. It is commonly used for success or error messages after form submissions:

flash.message = "Book saved successfully"
redirect(action: "list")

Render vs Redirect

Use render to output content directly and redirect to send the user to a different URL. Rendering returns the model to a GSP view, while redirecting triggers a new request.

Data Binding

Grails can bind request parameters directly to domain objects:

def update(Long id) {
    def book = Book.get(id)
    book.properties = params
    book.save()
}

Key Points

  • Controllers contain public action methods that handle requests.
  • Request parameters are automatically bound to action parameters.
  • The flash scope passes messages across redirects.
  • render outputs content; redirect sends the user elsewhere.
  • GORM list, get, and other methods retrieve data for views.
Share this post:

Comments (0)

Please login or register to comment.