grails
  • grails-controller
  • grails-3.0
  • 2016-05-14 52 views 1 likes 
    1

    好吧,我正在嘗試學習grails,我不明白UrlMappings是如何工作的。Grails控制器映射,完全誤解

    這是我的代碼:

    package naturalselector 
    
    class UrlMappings { 
    
    static mappings = { 
        "/pleasemapit"(view: '/index') 
        "/creatures/" { 
         controller = 'NaturalSelectionController' 
         action = 'viewCreatures' 
        } 
        "500"(view:'/error') 
        "404"(view:'/notFound') 
    } 
    } 
    

    Controller類:

    package naturalselector 
    
    class NaturalSelectionController { 
    
    def viewCreatures() { 
        println("HIT viewCreatures") 
        List creatures 
        6.times { idx -> 
        creatures.add(new RandomCreature()) 
        println creatures.get(idx) 
        } 
        redirect (view: "/index") 
    } 
    } 
    

    控制器處於的grails-app \控制器\ naturalselector \ UrlMappings在相同的目錄。

    在所有示例中,控制器都有一個小寫值。 我不明白。它是一個包嗎?爲什麼要將控制器指定爲一個包? 我只想在控制器中執行方法,我不想渲染任何頁面,只是重定向回到索引。謝謝。

    +0

    敢肯定你重定向到一個動作,而不是視圖。使用重定向(操作:「索引」),重定向應該工作。看看傑夫的答案。 – billjamesdev

    回答

    3

    它是一個包嗎?

    爲什麼你會指定控制器作爲一個整體?

    你不會。

    取而代之的是...

    static mappings = { 
        "/pleasemapit"(view: '/index') 
        "/creatures/" { 
         controller = 'NaturalSelectionController' 
         action = 'viewCreatures' 
        } 
        "500"(view:'/error') 
        "404"(view:'/notFound') 
    } 
    

    使用此...

    static mappings = { 
        "/pleasemapit"(view: '/index') 
        "/creatures" { 
         controller = 'naturalSelection' 
         action = 'viewCreatures' 
        } 
        "500"(view:'/error') 
        "404"(view:'/notFound') 
    } 
    

    或者這...

    static mappings = { 
        "/pleasemapit"(view: '/index') 
        "/creatures"(controller: 'naturalSelection', action: 'viewCreatures') 
        "500"(view:'/error') 
        "404"(view:'/notFound') 
    } 
    
    +0

    您可以在http://docs.grails.org/3.1.6/guide/theWebLayer.html#urlmappings上閱讀有關URL映射的更多信息。 –

    +0

    謝謝。這比我想象的要容易 – arseniyandru

    相關問題