我很难弄清楚如何让 spring 在表单绑定(bind)期间使用我的自定义错误消息来处理列表中对象字段上的错误。
上述问题的更清晰版本是:
我的类(class)如下所示:
public class Foo
{
private Long fooId;
private Long number;
//getters and setters stuff
}
然后是一个 Bar 类,其中 HAS-A
的 Foo
列表:
public class Bar
{
private List<Foo> foos;
//other stuff
}
如果我的 Bar 只有一个 Foo
,则使用以下消息键(在validation-text.properties中)
typeMismatch.bar.foo.number=Invalid data.
但是,因为我有一个 Foo
列表,所以该字段实际上是 foos[0].number
或 foos[1].number
等
很明显,typeMismatch.bar.foo
不会被解析为任何内容。
我的问题是,如何在 valid-text.properties 字段中指定类似的内容:
typeMismatch.bar.foos[*].number=Invalid data. ???
最佳答案
您可以通过检查 BindingResult
对象来检查可以在validation-text.properties 中使用哪些键。将 BindingResult result
添加为 Controller 方法的参数(如果您还没有),然后在发生验证错误时查看 result.getFieldError().getCodes() (这应该包含第一个字段错误的代码(如果有)。
编辑
我已经尝试了您的示例并检查了 BindingResult
中的代码。以下任何代码都应该有效
- typeMismatch.bar.foos[1].number
- typeMismatch.bar.foos.number
- typeMismatch.foos[1].number
- typeMismatch.foos.number
- typeMismatch.number
- typeMismatch.java.lang.Long
- 类型不匹配
因此,要获得您想要的结果,您只需在已经尝试过的内容中添加“s”(是 foos 而不是 foo):
typeMismatch.bar.foos.number=无效数据。
关于java - 如何在validation-text.properties 文件中使用通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493098/