Sunday 14 October 2012

Grails UrlMappings.groovy - Mapping a top level controller excludes dbconsole fix

One of the requirements in my app that I'm working on the side involves adding a rewriting rule that maps any top level context to the ProfileController. Initially, it looks like this:
 class UrlMappings {  
      static mappings = {  
           "/${screenName}" (controller: 'profile', action: 'profile')  
      }  
 }  
So far so good. Unfortunately this poses a problem when I wanted to goto the dbconsole, which is a tool exposed by Grails in development mode to check the contents of the H2 in-mem database. Since everything maps to that controller, even the dbconsole went there. There is a solution, and that involves the use of the `constraints` param. We simply just have to add a notEqual validator of 'dbconsole' so that it skips the controller mapping. Since the /dbconsole is defined as a servlet-mapping in web.xml, it will filter to that context after Grails decides it cannot handle that uri.
So here is the solution:
 class UrlMappings {  
      static mappings = {  
           "/${screenName}" {  
                controller = 'profile'  
                action = 'profile'  
                constraints { screenName(notEqual: 'dbconsole') }}  
      }  
 }  

1 comment: