Grails命令对象未绑定到'def'类型

问题描述 投票:0回答:1

[尝试将参数绑定到定义为'def'的命令对象字段时遇到问题。

我有以下命令对象:

package command

import grails.validation.Validateable

@Validateable
class TestBindCommand {

    String fieldType
    def fieldValue
}

我有以下控制器来测试参数是否已正确绑定:

package command.binding

import command.TestBindCommand

class TestBindingController {

    def index() { }

    def testBinding(TestBindCommand testBindCommand) {
        println("fieldType: " + testBindCommand.fieldType)
        println("fieldValue: " + testBindCommand.fieldValue)
        render("fieldType: ${testBindCommand.fieldType} - fieldValue: ${testBindCommand.fieldValue}")
    }
}

最后,我有以下ajax请求将参数发布到上面的testBinding方法:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Index</title>
</head>
<g:javascript library="jquery" plugin="jquery"/>
<script>
    $( document ).ready(function() {
        $.post('/command-binding/testBinding/testBinding', { fieldType: "String", fieldValue : "hello world"},
            function(returnedData){
                console.log(returnedData);
            });
    });
</script>
<body>
Index Page
</body>
</html>

如果将fieldValue的类型更改为String,它将开始绑定。如果您随后将其切换回def,它是否仍然有效?如果执行grails清理,然后将fieldValue设置为def来重新启动应用程序,则它将无法再次使用!?我已经调试到DataBindingUtils.java中,当它的类型为'def'时,似乎没有将该字段添加到白名单中。

示例项目可以在这里找到:

https://github.com/georgy3k/command-binding

Grails版本2.5.6

grails data-binding grails-2.0 grails-controller command-objects
1个回答
2
投票

我已经调试到DataBindingUtils.java中,类型为时,该字段不会添加到白名单中'def'。

这是正确的,并且是设计使然。默认情况下,动态类型的属性不参与质量属性数据绑定。

来自https://grails.github.io/grails2-doc/2.5.6/ref/Constraints/bindable.html

默认情况下不可绑定的属性是与瞬态字段,动态类型的属性和静态属性。

如果您真的想让动态类型的属性参与整体属性绑定,则必须使用类似这样的选项:

class TestBindCommand {

    String fieldType
    def fieldValue

    static constraints = {
        fieldValue bindable: true
    }
}

也就是说,对于命令对象,没有充分的理由要具有动态类型的属性。

我希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.