Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails UrlMapping Redirect to keep DRY

I am working with Grails 2.1.1 and would like to add a handful of customized URLs that map to Controller Actions.

I can do that, but the original mapping still works.

For example, I created a mapping add-property-to-directory in my UrlMappings as follows:

class UrlMappings {

    static mappings = {
        "/add-property-to-directory"(controller: "property", action: "create")
        "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

Now, I can hit /mysite/add-property-to-directory and it will execute PropertyController.create, as I would expect.

However, I can still hit /mysite/property/create, and it will execute the same PropertyController.create method.

In the spirit of DRY, I would like to do a 301 Redirect from /mysite/property/create to /mysite/add-property-to-directory.

I could not find a way to do this in UrlMappings.groovy. Does anyone know of a way I can accomplish this in Grails?

Thank you very much!

UPDATE

Here is the solution that I implemented, based on Tom's answer:

UrlMappings.groovy

class UrlMappings {

    static mappings = {

        "/add-property-to-directory"(controller: "property", action: "create")
        "/property/create" {
            controller = "redirect"
            destination = "/add-property-to-directory"
        }


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

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

RedirectController.groovy

class RedirectController {

    def index() {
        redirect(url: params.destination, permanent: true)
    }
}
like image 644
Philip Tenn Avatar asked Sep 27 '12 02:09

Philip Tenn


2 Answers

It is possible to achieve this:

"/$controller/$action?/$id?" (
    controller: 'myRedirectControlller', action: 'myRedirectAction', params:[ controller: $controller, action: $action, id: $id ]
)

"/user/list" ( controller:'user', action:'list' )

and in the action you get the values normallny in params:

log.trace 'myRedirectController.myRedirectAction: ' + params.controller + ', ' + params.action + ', ' + params.id
like image 180
Tom Metz Avatar answered Oct 29 '22 14:10

Tom Metz


As of Grails 2.3, it is possible to do redirects directly in the UrlMappings, without the need for a redirect controller. So in case you ever upgrade, you can redirect in UrlMappings like so, as per the documentation:

"/property/create"(redirect: '/add-property-to-directory')

Request parameters that were part of the original request will be included in the redirect.

like image 2
AForsberg Avatar answered Oct 29 '22 14:10

AForsberg