In my Grails app I have a couple of domain classes, say Author and Book. I'm using the default URL mappings:
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
}
So the relative URL to show the book with id 2 is /book/show/2. To show the author with id 5 it's /author/show/5. Both the Author and Book classes have a name property, but this is not guaranteed to be unique.
For SEO reasons, I would like to include this name in these URLs e.g. change the URL to show a book to /book/show/2/the+davinci+code and the URL to show an author to /author/show/5/dan+brown.
To prevent breaking any existing (external) links to my pages, I would ideally like to support both formats, such that either of the following will show Dan Brown's page
/author/show/5/author/show/5/dan+brownWhat's the easiest way for me to get from where I am now (URLs with ID only), to where I want to be (URLs with ID and name also supported)?
Don,
you have two options. First, if you do not plan to use name in your logic at all (which seems like an option, because you already have unique id), then you can modify url mapping in following way:
static mappings = {
"/$controller/$action?/$id?/$extra?"{
constraints {
// apply constraints here
}
}
}
This will add extra optional parameter to all requests. If you want to do it only for Author and Book controller, then you you should modify your UrlMappings.groovy like this
static mappings = {
"/author/show/$id?/$name?" (controller:"author", action: "show")
"/book/show/$id?/$name?" (controller:"book", action: "show")
"/$controller/$action?/$id?" {
constraints {
// apply constraints here
}
}
}
First two rules will match urls like "/author/show/10/dan+brown" as well as just "/author/show/10" and you can access the name parameter from show method via params.name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With