我遇到了一个问题,我在查询字符串上使用format=json
参数向 Grails 1.3.7 发送了一个POST。
基于Grails withFormat
文档 - http://grails.org/doc/1.3.7/ref/Controllers/withFormat.html,此参数应该使withFormat
闭包在其中执行json
闭包。
即:
withFormat {
json {
// this logic should be executed if the query string has format=json
}
}
在这种情况下,控制器方法正在提供多种内容类型。有些逻辑应该仅针对表单运行,因此添加了withFormat
闭包,如下所示:
withFormat {
form {
// form specific logic
}
}
注意没有json
块,因为如果这是一个json请求,则没有相应的逻辑可执行。问题是,即使我们在查询字符串上发送format=json
的请求,表单块也在执行。
为什么会发生这种情况?
答案 0 :(得分:4)
显然,如果你没有在withFormat中指定匹配的闭包,Grails仍会运行一个。 Grails文档确实注意到,如果请求格式是" all",它将执行withFormat块中的第一个闭包。我想如果你的请求格式与withFormat块中的一个闭包没有匹配,Grails默认运行第一个闭包。
为了解决这个问题,我们在withFormat中放置了一个空的json闭包,Grails按照预期处理了所有内容。
withFormat {
json {
// do nothing
}
form {
// form specific logic
}
}