Search code examples
grailsurl-mapping

Grails UrlMapping route to fixed controller and action


I made the following rule in my UrlMapping file and now all my controllers are matching to the ("/$username") mapping, not the first one ("/$controller/$action?/$id?").

The idea here was to list all public items from an user using a short url. It works but it breaks all others controllers.

static mappings = {

    "/$controller/$action?/$id?"{
        constraints {
            // apply constraints here
        }
    }

    "/$username" {
        controller = 'user'
        action = 'publicItens'
    }

    "/"(controller:'usuario', action: 'index' )
    "500"(view:'/error')
}

How can I map it correctly?


Solution

  • solved!

    I just wrote some code in the UrlMappings to create rules automatically for each controller in the application. Using this approach when the user types /appname/controllerName then the rule created automatically is considered in place of the "$/username" rule.

    The critical point is that the use of ApplicationHolder which is deprecated. That can fixed writing your own ApplicationHolder.

    static mappings = {
    
        //creates one mapping rule for each controller in the application
        ApplicationHolder.application.controllerClasses*.logicalPropertyName.each { cName ->
            "/$cName" {
                controller = cName
            }
        }
    
        "/$controller/$action?/$id?"{
        }
    
        "/$username" {
            controller = 'usuario'
            action = 'itensPublicos'
        }
    
        "/"(controller:'usuario', action: 'index' )
        "500"(view:'/error')
    }