Sharing the Code

Programming stuff that might be useful to others

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.

grails-app/conf/UrlMappings.groovy:

[sourcecode language=”java”]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”]
}
}
}
[/sourcecode]

The GET, POST etc refer to the HTTP method. So calling the URL “/api/1.0/recipes” would call the list action on a GET request and the save action on a POST request.

1 Trackback
grailstutorial.org

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 t…

 

Comments are closed