0

尝试将参数绑定到定义为“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 clean 并在 fieldValue 设置为 def 的情况下重新启动应用程序,那么它将无法再次工作!?我已经调试到 DataBindingUtils.java 并且当它是“def”类型时,它似乎没有被添加到白名单中。

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

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

Grails 2.5.6 版

4

1 回答 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
    }
}

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

我希望这会有所帮助。

于 2020-04-02T16:27:06.003 回答