0

在 Grails 2.5.0 中,是否可以将 JSON POST 正文中的属性值注入到不是命令对象的控制器操作方法参数中?例如,转换为字符串、原语等。

这在 Grails 2.2.4 中是可能的,但我还没有找到在 2.5.0 中做到这一点的方法。

(我知道查询字符串值可以注入到 Grails 2.5.0 和 2.2.4 中的控制器操作方法参数中)

4

1 回答 1

0

请参阅http://grails.github.io/grails-doc/2.3.0/guide/introduction.html#whatsNew23中的将请求正文绑定到命令对象部分。它在 Grails 2.3.x 中有所改变。基本上,如果您尝试访问请求 JSON 两次,您将无法使用它,因为 Grails 在解析数据后关闭请求流并使用它来绑定任何 CommandObject 或任何域实例(作为命令对象)。

因此,如果您将请求 JSON 传递给操作,请说 support:{"foo": "bar"}并且您正在尝试这样做:

class SomeController {

    def test(String foo) {
        println foo        // Will be null
        println request.JSON.foo           // Will be "bar"
    }
}

相反,任何域类绑定现在都可以工作:

class MyDomainClass {

     String foo
}

并修改控制器动作:

class SomeController {

    def test(MyDomainClass domainInstance) {
        println domainInstance.foo        // Will be "bar"
        println request.JSON           // Will be null since request stream is closed and binded to the domainInstance
    }
}
于 2015-07-04T07:34:25.577 回答