来自 JSON POST 正文的 Grails 2.5.0 Controller 操作方法参数

标签 grails controller grails-2.2 grails-2.5

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

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

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

最佳答案

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

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

class SomeController {

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

相反,任何域类绑定(bind)现在都可以工作:
class MyDomainClass {

     String foo
}

并修改 Controller Action :
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
    }
}

关于来自 JSON POST 正文的 Grails 2.5.0 Controller 操作方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216301/

相关文章:

grails - 嵌入式Grails脚手架

java - Grails Hibernate session 问题 - 未能延迟初始化集合

Grails:如何通过过滤器中的 Controller 名称获取 Controller ?

mongodb - MongoTimeoutException 消息 : Timed out while waiting to connect after 10000 ms

java - 在 spring Controller 中注入(inject)类对象的方法?

ruby-on-rails - rails : prepend_before_action in superclass

oracle - Grails - 如何在不放入/lib 的情况下将 Oracle jdbc jar 添加到类路径?

grails - 将在一个 Controller 中查询的记录传递给Grails中的另一个 Controller

javascript - AngularJs 将参数值传递给 Controller

grails - Gradle插件不适用于Grails 2.2.3