Grails Goodness: Namespace Support for Controllers

In a Grails application we can organize our controllers into packages, but if we use the same name for multiple controllers, placed in different packages, then Grails cannot resolve the correct controller name. Grails ignores the package name when finding a controller by name. But with namespace support since Grails 2.3 we can have controllers with the same name, but we can use a namespace property to distinguish between the different controllers.

We can add a new static property to a controller class with the name namespace. The value of this property defines the namespace. We can then write new URL mappings in the grails-app/conf/UrlMappings.groovy file and use the namespace value as a mapping attribute.

Suppose we have two ReportController classes in our application. One is defined as com.mrhaki.grails.user.ReportController and the other as com.mrhaki.grails.common.ReportController. The following code samples show sample implementations for both controllers:

And the second controller:

In our UrlMappings.groovy file we can now add two extra mappings for these controllers and we use the new namespace attribute to point the mapping to the correct controller implementation.

The namespace support is also useful in building RESTful APIs with Grails. We can use the namespace attribute to have different versions for the same controller. For example in the following UrlMappings.groovy configuration we have two mappings to a controller with the same name, but the namespace attribute defines different version values:

To create links to controllers with a namespace we can use the new namespace attribute in the link and createLink tags. The following GSP page part shows how we can set the namespace so a correct link is generated:

We get the following HTML:

Code written with Grails 2.3.2.

Original article

This entry was posted in Coding, Grails by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">