grailsgroovygrails-controllergrails-3.1urlmappings.groovy

How to disable default URL mappings for some actions


I'm using Grails version 3.1.12.

I want to disable some default URL mappings for actions in order to manage them manually. For example, given the controller:

class MyController {

    myAction() {
        render('Hello')
    }
}

This action maps by default to my/myAction, however I want to disable this mapping and use a custom one like this one defined in UrlMappings.groovy:

static mappings {

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

    '/myCustomAction'(controller: 'my', action: 'myAction')
}

The /$controller/$action... mapping ships by default when creating the Grails project for the first time and provides the default convention which I still want for some other actions, however I want to exclude the default mapping for myAction. I have tried using the excludes setting in UrlMappings.groovy:

static excludes = ['/my/myAction']

However, the endpoint my/myAction keeps responding to the default mapping.

How can I achieve the desired behavior?


Solution

  • The route my/myAction is being generated by the default /$controller/$action mapping. As such you will need to edit the constraints section of that mapping in order to exclude your controller, something like this should work (albiet some what ugly):

    "/$controller/$action?/$id?(.$format)?"{
        constraints {
            controller(validator: { return it != 'my'})
        }
    }