15 September 2009

Cool things with Grails URL mapping

In Grails you have a lot of nice features for doing web development. One of them is URL mapping with the link tag.
Grails default mapping is this:
"/$controller/$action?/$id?" {}
This will map the URL 'http:localhost:8080/myapp/book/show/1' to the action show in the BookController class. To create such links you can use the link tag like this:
<g:link controller="book" action="show" id="book.id">
  ${book.title}
</g:link>
Sure this is the standard way. But now lets change the URL mapping by replacing the default mapping:
"/$book/$id?"(controller: "book", action: "show")
This will tell Grails to map the URL 'http:localhost:8080/myapp/book/1' to the same show action as above, but what's happening with our link?
It's stil working! Grails knows, that URLs, which are pointing to BookControllers's show action have to be of the declared structure and thus, the link tag will create a URL like 'http:localhost:8080/myapp/book/1'.

Ok, let's go on. What else can we do with this?
By default the URL 'http:localhost:8080/myapp/book/list?year=2009' will point to the list action of BookController and the URL parameter year will be available with
params.year
in the action. To create this URL you can use the link tag again:
<g:link controller="book" action="list" params="[year: "2009"]">
  Books released in 2009
</g:link>
Now let's change our mapping again by adding:
"/$books/$year?"(controller: "book", action: "list")
Well, now the above link will create the URL 'http:localhost:8080/myapp/books/2009' and everything else will stil work as expected.