3
votes

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?

1
from_age in url mapping won't match with to_age string used in sample url. User wont get anything. - dmahapatro
Yes that's my point, I need to find a way of creating the mapping dynamically so foo/bar becomes ?foo=bar regardless of what foo or bar are - user404345

1 Answers

2
votes

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])