Question

I am trying to rewrite my urls for a particular controller (and action) for example:

www.mysite.com/user/search?sex=male&from_age=18&to_age=19

would become

www.mysite.com/user/search/sex/male/from_age/18/to_age/19

I know I could do this using Grails' url rewriting along the lines of:

"/user/search/sex/$Sex/from_age/$from_age/to_age/$to_age" {
  controller = 'user'
  action = 'search'
}

The problem I face is that a user could just as easily trigger a url like:

www.mysite.com/user/search/sex/male/to_age/19/location/chicago

i.e. the url is dynamic based on the search criteria entered by the user in the search form

Is there anyway of dynamically rewriting the urls along the lines of Apache's mod_rewrite so I could have param_name/param_value instead of ?param_name=param_value?

Was it helpful?

Solution

You can map a wildcard url to your search action, but you will have to perform the parsing of the parameters yourself:

UrlMappings.groovy:

"/user/search/$query**" {
    controller = 'user'
    action = 'search'
}

This would give you everything after the static portion of the url as a single string.

i.e. www.mysite.com/user/search/sex/male/to_age/19/location/chicago would give you params.query = 'sex/male/to_age/19/location/chicago'

However, these kind of urls don't participate in dynamic url rewriting, so you would have to build the urls yourself when attempting to link to it.

quick unsafe (unescaped) example of transforming a paramMap into that style of query string:

def queryStr = params.collect({ n,v -> "$n/$v" }).join('/')
g.createLinkTo(controller: 'user', action: 'search', params: [query: queryStr])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top