grailsgrails-3.0.9urlmappings.groovy

URL Mapping - Replacing characters in a parameter pulled from a database


I am currently trying to figure out, how to modify the parameter being integrated into the URL Mapping I am using.

static mappings = 
{

"/$controller/$action?/$id?/(.$format)?"
{
        constraints {
            // apply constraints here
        }

}


name test1: "/.../$title/..."{
        controller = "study"
        action = "st_show"
    }

name test2: "/.../$title/..."{
        controller = "search"
        action = "se_show"
    }

The parameter $title is pretty much a dataset, which is pulled from a database and which will get transmitted in the following format [ this is a title ]. So there are square brackets in front and behind the string and words are seperated through blanks.

If I am creating a link through g:link now with the params nested in, it gets put into the url as it is pulled from the database. What I am attempting is to create SEO-URLs, which will present a certain title of a publication devided by hyphens instead of url-encoded "%20".

Until now, I was able to generate dynamic urls looking like this:

http://localhost:8080/projectname/show/%5BAllgemeine%20Bevölkerungs[...]/782/...PARAMS...

Furthermore I already implemented it through JQuery, though it should be static and users should be able to copy the link to open up the page themselves - that wouldn't be possible when changing the url client-side while loading up the page.

Is there a way to define a function with something like replaceAll.(' ', '-'), which can be invoked onto the parameter in the mapping to replace blanks with hyphens and f.e. square brackets with an empty character? That's pretty much, what I wasn't able to come by through the documentation.

Thank you already in advance for your help!


Solution

  • I managed to solve my problem by creating a service with a function containing a regex and executing this function onto the parameter title in my g:link, which I firstly converted to a string, which gets passed to the function.

    <g:link controller="study" action="st_show" params="[data: data, ... title: ConversionService.convert(fieldValue(bean: path).toString(), ... data: data)]"></g:link>
    

    And the function in the ConversionService

    public static String convert(String title){
            title = title.replaceAll("\\s", "-").replaceAll("[^0-9a-zA-Z\\-]", "");
            return title;
    }