Grails UrlMapping Redirect to keep DRY

半世苍凉 提交于 2019-12-10 12:52:36

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/12613133/grails-urlmapping-redirect-to-keep-dry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!