如何在grails 2.3.0控制器中重定向和响应保存操作

时间:2014-05-10 16:25:15

标签: grails controller

request.withFormat {
            form {
                redirect humanInstance
                //Explain : old grails redirect like   redirect(action: "show", id: humanInstance.id) 
                //but in 2.3.0 by  redirect humanInstance  this statement i saw it goes to  def show(Human humanInstance)  action
                //Q1: how it understand that it has to redirect  def show(Human humanInstance) action ?
                //cause here so many methods which receives humanInstance
                //Q2: And where it get processed ?
            }
            '*' {
                respond humanInstance, [status: CREATED]
            }
            //Explain : I tested it that in the above {works for normalCall}'*'{works for restCall}
            //Q3: What is '*' operator do here what it's name?
        }

1 个答案:

答案 0 :(得分:2)

'*'是一种全能型,它与一个代码块相关联,如果没有其他块与accept头匹配,则应该执行该代码块。请参阅以下内容......

request.withFormat {
    xml {
        // execute this if the request content type is xml
    }
    json {
        // execute this if the request content type is json
    }
    '*' {
        // execute this if neither of the other 2 matched the request's content type
    }
}

您可能希望了解这一点,包括您已配置的mime类型。您应该查看http://grails.org/doc/2.3.x/guide/theWebLayer.html#contentNegotiation上的官方用户指南的“内容协商”部分。

我希望这有用。

<强>更新

当你调用redirect(someDomainClassInstance)时,你最终会在https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/plugins/web/api/ControllersApi.java#L270

调用https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/plugins/web/api/ControllersApi.java#L248

调用https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java#L160

调用https://github.com/grails/grails-core/blob/v2.3.8/grails-web/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultLinkGenerator.groovy#L175

此时“method”的值为“GET_ID”。与GET_ID相关联的https://github.com/grails/grails-core/blob/v2.3.8/grails-web/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultLinkGenerator.groovy#L56中的值为“show”,这就是您将重定向到show方法的原因。