Sunday, October 6, 2013

Grails and dynamic controller names in UrlMappings

I was creating some REST web services and I needed to map a URL like “/api/1.0/recipes” to a controller called RecipesRestController. It took me a while to work out how to generate a dynamic controller name from the request path. The trick is not to use $controller, it doesn’t seem to work, so instead I renamed it $aController.


class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }
        "/"(view:"/index")
        "500"(view:'/error')
        "/api/1.0/$aController"{
            controller={"${params.aController}Rest"}
            action=[GET:"list", POST:"save"]
        }
        "/api/1.0/$aController/$id"{
            controller={"${params.aController}Rest"}
            action=[GET:"show",  PUT:"update", DELETE:"delete"]
        }
    }
}

 

OR

 
import org.codehaus.groovy.grails.commons.ApplicationHolder

class UrlMappings {
  static mappings = {        
    for( controllerClass in ApplicationHolder.application.controllerClasses) {
      // Admin Controllers first
      if( controllerClass.name.startsWith("Admin")){
        // note... fixes the case so that AdminUserController maps to /admin/user
        "/admin/${controllerClass.name[5].toLowerCase() + controllerClass.name[6..-1]}/$action?/$id?" {
          controller = "admin${controllerClass.name[5..-1]}".toString()
        }
      }
    }
  }
}
 

OR


    "/admin/$controller/$action?/$id?"{
        controller = {
            def controllerName = (request.requestURI - request.contextPath).split('/')[2]

            // or
            //def controllerName = request.servletPath.split('/')[2]

            "${controllerName}Admin"
        }
    }

No comments:

Post a Comment