Over a million developers have joined DZone.

Grails Controller namespaces

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

Grails 2.3 introduced controller namespaces. This feature gives Grails developers the option to have multiple controllers that use the same name (within different packages).

It is not that hard to get into a situation where you want two or more controllers with the same name.

Assume we have an application that gives users the option to update their personal profile settings. We might have a ProfileController for this. Now we might also need an administration backend which gives administrators the option to update user profiles. ProfileController would again be a good name for handling these kinds of requests.

With Grails 2.3 we can now do this by adding namespaces to controllers using the static namespace property:

package foo.bar.user
 
class ProfileController {
 
  static namespace = 'user'
 
  // actions that can be accessed by users
}

package foo.bar.admin
 
class ProfileController {
 
  static namespace = 'admin'
 
  // actions that can be accessed by administrators
}
We can now use the namespace to map the controllers to different URLs within UrlMappings.groovy:

class UrlMappings {
 
  static mappings = { 
    '/profile' { 
      controller = 'profile' 
      namespace = 'user' 
    }
    '/admin/profile' { 
      controller = 'profile' 
      namespace = 'admin' 
    }
    ..
  }
}

To make the namespace part of the URL by default we can use the $namespace variable:

static mappings = { 
  "/$namespace/$controller/$action?"() 
}
Using this way we are able to access our controllers with the following URLs:

/user/profile/<action>
/admin/profile/<action>

Please note that we also need to provide the namespace when building links:

1
	
<g:link controller="profile" namespace="admin">Profile admin functions</g:link>

Learn tips and best practices for optimizing your capacity management strategy with the Market Guide for Capacity Management, brought to you in partnership with BMC.

Topics:

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}