2012-09-27 30 views
8

我與Grails 2.1.1工作,想添加自定義的URL映射到控制器動作屈指可數。Grails的urlMapping中重定向保持乾燥

我可以做到這一點,但原始的映射仍然有效。

例如,我在創建UrlMappings映射add-property-to-directory如下:

class UrlMappings { 

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

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

現在,我可以打/mysite/add-property-to-directory,它會執行PropertyController.create,正如我所期望的。

但是,我仍然可以按/mysite/property/create,它會執行相同的PropertyController.create方法。

本着DRY的精神,我想做一個301重定向從/mysite/property/create/mysite/add-property-to-directory

我找不到在UrlMappings.groovy中這樣做的方法。有沒有人知道我可以在Grails中實現這一點的方法?

非常感謝!

UPDATE

這裏是我實現的解決方案的基礎上,湯姆的回答是:

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

目前尚不可能。有一項功能請求可以指定URL映射中的重定向 - 請參閱http://jira.grails.org/browse/GRAILS-5994 –

+0

@sudhir謝謝,這回答了我的問題。您能否將您的評論複製到答案中,以便我可以接受它? –

+0

@sudhir,謝謝你的評論和有用的鏈接......湯姆編輯了他的答案,它引導我走在正確的軌道上去做所尋找的事情,所以我接受了他的答案。 –

回答

3

有可能實現這一目標:

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

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

,並在行動你得到的值normallny在PARAMS:

log.trace 'myRedirectController.myRedirectAction: ' + params.controller + ', ' + params.action + ', ' + params.id 
+0

感謝您的回答,但我不能將主映射更改爲重定向控制器,因爲我有其他控制器遵循'controller/action/id'的Grails約定。我希望能夠做明確的重定向。 –

+0

如果您只有一小部分控制器與標準映射,您可以準備其他特定規則。我已更新我的評論以包含一個。 –

+0

謝謝,湯姆。我接受了你的回答,這使我走上了正確的道路。我實際上最終創建了'RedirectController',但不是將'/ $ controller/$ action?/ $ id?'映射到它,而是爲它創建了一個'property/create'條目,並且將爲每個URL –

0

由於Grails的2.3,這是可以做到直接在重定向UrlMappings,而不需要重定向控制器。所以,如果你曾經升級,可以在UrlMappings重定向像這樣,按照該documentation:那是原始請求的一部分

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

請求參數將被列入重定向。