java Spring - 如何从 BindingResult 中删除“FieldError”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12514587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring - How to remove a `FieldError` from a BindingResult?
提问by th3an0maly
I have a BindingResult result
that has a FieldError
registered for the field date
. How can I remove this error?
我有一个BindingResult result
已经FieldError
注册的领域date
。我怎样才能消除这个错误?
Assume the error was added as result.rejectValue("date", "my_code", "my_message") ;
假设错误被添加为 result.rejectValue("date", "my_code", "my_message") ;
Thanks in advance
提前致谢
采纳答案by GreyBeardedGeek
Well, first of all, BindingResult is an interface, not a concrete class, and the interface doesn't specify any way to remove an error.
嗯,首先,BindingResult 是一个接口,而不是一个具体的类,并且该接口没有指定任何消除错误的方法。
Depending on which implementation of the interface you are dealing with, there may be a method (beyond what's specified in the BindingResult interface) to do this, but it seems unlikely.
根据您正在处理的接口的实现,可能有一种方法(超出 BindingResult 接口中指定的内容)来执行此操作,但似乎不太可能。
The only thing that I can think of is to create a new BindingResult instance, then loop through the errors and re-create all but the one that you want to ignore in the new one.
我唯一能想到的就是创建一个新的 BindingResult 实例,然后遍历错误并重新创建所有错误,但要在新的错误中忽略的除外。
回答by Ammar Akouri
Here is an example that implements @GreyBeardedGuy Answer, Suppose you want to remove the error
linked to a field
called specialField
in the class
MyModel
with a modelAttribute
name as myModel
from BindingResult
result
:
下面是一个例子,它实现@GreyBeardedGuy答案,假设你要删除的error
链接到一个field
名为specialField
在class
MyModel
同一个modelAttribute
名称myModel
来自BindingResult
result
:
List<FieldError> errorsToKeep = result.getFieldErrors().stream()
.filter(fer -> !fer.getField().equals("specialField "))
.collect(Collectors.toList());
result = new BeanPropertyBindingResult(vacancyDTO, "vacancyDTO");
for (FieldError fieldError : errorsToKeep) {
result.addError(fieldError);
}
回答by John Vint
The important question is, how did it get there in the first place? I assume date
is a java.util.Date field and the binding failed because of a formatting issue?
重要的问题是,它最初是如何到达那里的?我假设date
是一个 java.util.Date 字段并且由于格式问题绑定失败?
For instance you put in 01/01/1970
and it expected 1970-01-01
or something similar? The reason here is because Spring MVC has a default date binder. It needs to take a string representation of a date and turn it into a java.util.Date and failed because it doesnt match the appropriate format.
例如,您输入01/01/1970
并期望它1970-01-01
或类似的东西?这里的原因是因为 Spring MVC 有一个默认的日期绑定器。它需要采用日期的字符串表示形式并将其转换为 java.util.Date 并失败,因为它与适当的格式不匹配。
Take a look at @InitBinderand how to override the string-to-dateconversion to accept different formats.
看看@InitBinder以及如何覆盖字符串到日期的转换以接受不同的格式。