gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:03:28 25 4
gpt4 key购买 nike

尝试将参数绑定(bind)到定义为“def”的命令对象字段时遇到问题。

我有以下命令对象:

package command

import grails.validation.Validateable

@Validateable
class TestBindCommand {

String fieldType
def fieldValue
}


我有以下 Controller 来测试参数是否正确绑定(bind):
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,它将开始绑定(bind)。如果你再把它切换回def它仍然有效?!如果您执行 grails clean 并在 fieldValue 设置为 def 的情况下重新启动应用程序,那么它将无法再次工作!?我已经调试到 DataBindingUtils.java 并且当它是“def”类型时,它似乎没有被添加到白名单中。

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

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

Grails 2.5.6 版

最佳答案

I've debugged down into the DataBindingUtils.java and it appears that the field isn't getting added to the whitelist when it is of type 'def'.



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

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

Properties which are not bindable by default are those related to transient fields, dynamically typed properties and static properties.



如果你真的想让一个动态类型的属性参与批量属性绑定(bind),你必须选择这样的东西:
class TestBindCommand {

String fieldType
def fieldValue

static constraints = {
fieldValue bindable: true
}
}

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

我希望这会有所帮助。

关于Grails 命令对象未绑定(bind)到 'def' 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60990362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com