我有一个创建和保存方法如下:
def create () {
def myColorInstance = new Color()
return (colorInstance: myColorInstance]
}
def save () {
Date someDate = params.date("somedate", "MM/dd/yyyy")
int someInt = params.int("someInt")
color = colorService.add(params.colorname, someDate, someInt)
if (color.hasErrors())
render (view: "create", model: [colorInstance: color])
else
redirect (action: "list")
}
在我的布局页面上,我有以下内容:
<g:hasErrors>
<div class="alert alert-error">Please try submitting again</div>
</g:hasErrors>
我得到的行为是,当用户输入内容并且验证失败时。他们看到消息Please try submitting again
并且网址更改为http://localhost:8080/myapp/color/save
所以现在当他们第二次提交时(再次没有输入任何内容)然后我的应用程序失败并显示消息:“无法将类''转换为对象'null' null'to class'int'。尝试'java.lang.Integer'而不是“
什么是处理此类情况的最佳方法?我希望用户在顶部看到错误消息,他们应该能够再次纠正错误并尝试再次提交,它应该工作..
答案 0 :(得分:1)
您无法将int
设置为null,这是params.int("")
可能返回的内容。但是,Integer
可以为null。
Integer someInt = params.int("someInt")
这将修复您的异常,但它返回null的原因与您的视图无关,而不是首先传递数据。
仅供参考,这是不正确的语法:
def create () {
def myColorInstance = new Color()
return (colorInstance: myColorInstance]
}
应该是:
def create () {
[colorInstance: new Color()]
}