Blacktiger
Blacktiger

Reputation: 1275

Mapping controller names to urls (with packages)

Is it possible to configure grails to resolve controllers and actions using the package they are in as sub-folders?

For example, say I have the following directory structure:

/grails-app/controllers/HomeController.groovy (with action index)
/grails-app/controllers/security/UserController.groovy (with actions index, edit)
/grails-app/controllers/security/RoleController.groovy (with action index, edit)

I would like grails to generate the following url mappings automatically:

http://localhost:8080/myApp/ => HomeController.index
http://localhost:8080/myApp/security/user/ => UserController.index
http://localhost:8080/myApp/security/user/edit => UserController.edit
http://localhost:8080/myApp/security/role/ => RoleController.index
http://localhost:8080/myApp/security/role/edit => RoleController.edit

Upvotes: 1

Views: 5848

Answers (2)

Rob Hruska
Rob Hruska

Reputation: 120456

I would be a bit wary of mapping them directly to your package names. Doing that will make it very hard for you to refactor in the future, especially once your application is out in the wild. It's also going against the conventional nature of Grails.

However, you can still manually structure your URLs to map to different paths. For your question, here's an example:

// grails-app/conf/UrlMappings.groovy

'/security/user/$action?/$id?' (controller: 'user')
'/security/role/$action?/$id?' (controller: 'role')

// the rest of the default UrlMappings are below
'/$controller/$action?/$id?' {}

Since controllers are typically referenced by name, e.g. "user" in your case, it's not easy to go against this convention; it'd be trying to fight the framework instead of letting it do the work for you.

It's probably possible to do this based on package (maybe using Reflection, or something?), but not advisable.

Upvotes: 3

John Engelman
John Engelman

Reputation: 4439

I believe you are looking for Grails URLMapping constraint. Look here: Grails - URL mapping

Upvotes: 1

Related Questions