Grails中的新代码生成了控制器

时间:2014-06-11 05:47:17

标签: grails grails-controller

由于我升级了Grails版本,因此控制器保存方法中生成的代码已更改。我已经阅读了单独解释每个项目的文档,但如果有人能够全面解释request.withFormat部分,那将会很棒。

以下代码段取自自动生成的Save操作。令我困惑的一件事是。这里的哪一行表示,渲染"显示"成功保存操作后查看?

def save(User userInstance) {
    if (userInstance == null) {
        notFound()
        return
    }

    if (userInstance.hasErrors()) {
        respond userInstance.errors, view:'create'
        return
    }

    userInstance.save flush:true

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.created.message', args: [
                message(code: 'user.label', default: 'User'),
                userInstance.id
            ])
            redirect userInstance
        }
        '*' { respond userInstance, [status: CREATED] }
    }
}    

2 个答案:

答案 0 :(得分:3)

request.withFOrmat可用于返回不同的响应类型,具体取决于请求接受标头。

documentation

中的示例
request.withFormat {
    html bookList:books // render html
    js { render "alert('hello')" } // render javascript
    xml { render books as XML } // render xml
}

在您的示例中,控制器可以返回两种类型的响应。一个用于多部分表单请求,另一个用于所有其他请求:

request.withFormat {
    form multipartForm {
        // if it is a multipart form request -> add a flash message and redirect to another action
        flash.message = message(code: 'default.created.message', args: [
            message(code: 'user.label', default: 'User'),
            userInstance.id
        ])
        redirect userInstance
    }
    '*' { 
         // for all other request types, respond with the `userInstance` object
         respond userInstance, [status: CREATED] 
    }
}

答案 1 :(得分:1)

这似乎是一种未记录的重定向行为。但是看看grails代码,我们可以看出它使用了这个约定:

如果重定向仅将PERSISTED对象作为参数,则它将推断show action url并使用object id作为url参数。

https://jira.grails.org/browse/GRAILS-11862处有针对该文档问题的Jira

更多资源: http://grails.1312388.n4.nabble.com/New-controller-syntax-explained-td4654914.html

关于withFormat片段,它包含三种情况:
1)"形式"一个简单的表单提交,用于检测html响应(enctype =" application / x-www-form-urlencoded")
2)" multipartForm"文件上传表单提交请求html响应(enctype =" multipart / form-data")
3)" *"所有其他选项,例如restfull请求中的json或xml
情况1和2由相同的代码处理。

相关问题