Search

Dark theme | Light theme

February 27, 2012

Grails Goodness: Binding Method Arguments in Controller Methods

Since Grails 2.0 we can use methods instead of closures to define actions for our controllers. We already could pass a command object to a method as argument, but we can also use primitive typed arguments in our method definition. The name of the argument is the name of the request parameter we pass to the controller. Grails will automatically convert the request parameter to the type we have used in our method definition. If the type conversion fails then the parameter will be null.

Let's create a method in a controller with three arguments: a String typed argument with the names author and book. And an argument with type Long with the name id.

// File: grails-app/controllers/sample/MethodSampleController.groovy
package sample

class MethodSampleController {
    /**
     * Sample method with 3 arguments.
     *
     * @param author Name of author
     * @param id Identifier for author
     * @param book Book title 
     */
    def sample(final String author, final Long id, final String book) {
        render "Params: author = $author, book= $book, id = $id"
    }

}

If we invoke our controller with http://localhost:8080/grails-samples/methodSample/sample?id=100&book=It&author=Stephen%20King we get the following output:

Params: name= Stephen King, book = It, id = 100

Suppose we don't provide a valid long value for the id parameter we see in the output id is null. We use the following URL http://localhost:8080/grails-samples/methodSample/sample?id=1a&book=The%20Stand&author=Stephen%20King.

Params: author = Stephen King, book = The Stand, id = null

After reading this blog post and looking at the Grails documentation I learned we can even change the name of the argument and map it to a request parameter name with the @RequestParameter annotation. So then the name of the argument and the request parameter don't have to be the same.

Let's change our sample method and see what the output is:

// File: grails-app/controllers/sample/MethodSampleController.groovy
package sample

import grails.web.RequestParameter

class MethodSampleController {
    /**
     * Sample method with 3 arguments.
     *
     * @param author Name of author
     * @param id Identifier for author
     * @param book Book title 
     */
    def sample(final String author, @RequestParameter('identifier') final Long id, @RequestParameter('bookTitle') final String book) {
        render "Params: author = $author, book = $book, id = $id"
    }

}

Now we need the following URL to see correct output: http://localhost:8080/controllers/author/sample?bookTitle=It&identifier=200&author=Stephen%20King.

Params: name= Stephen King, book = It, id = 200