Java 如何从 BindingResult 获取控制器中的错误文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2751603/
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
How to get error text in controller from BindingResult
提问by Mike
I have an controller that returns JSON. It takes a form, which validates itself via spring annotations. I can get FieldError list from BindingResult, but they don't contain the text that a JSP would display in the tag. How can I get the error text to send back in JSON?
我有一个返回 JSON 的控制器。它采用一种形式,通过 spring 注释来验证自己。我可以从 BindingResult 获取 FieldError 列表,但它们不包含 JSP 将在标记中显示的文本。如何让错误文本以 JSON 形式发回?
@RequestMapping(method = RequestMethod.POST)
public
@ResponseBody
JSONResponse submit(@Valid AnswerForm answerForm, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {
if (result.hasErrors()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
JSONResponse r = new JSONResponse();
r.setStatus(JSONResponseStatus.ERROR);
//HOW DO I GET ERROR MESSAGES OUT OF BindingResult???
} else {
JSONResponse r = new JSONResponse();
r.setStatus(JSONResponseStatus.OK);
return r;
}
}
JSONREsponse class is just a POJO
JSONREsponse 类只是一个 POJO
public class JSONResponse implements Serializable {
private JSONResponseStatus status;
private String error;
private Map<String,String> errors;
private Map<String,Object> data;
...getters and setters...
}
Calling BindingResult.getAllErrors() returns an array of FieldError objects, but it doesn't have the actual errors.
调用 BindingResult.getAllErrors() 会返回一个 FieldError 对象数组,但它没有实际的错误。
采纳答案by Arthur Ronald
Disclaimer: I still do not use Spring-MVC 3.0
免责声明:我仍然不使用 Spring-MVC 3.0
But i think the same approach used by Spring 2.5 can fullfil your needs
但我认为 Spring 2.5 使用的相同方法可以满足您的需求
for (Object object : bindingResult.getAllErrors()) {
if(object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
System.out.println(fieldError.getCode());
}
if(object instanceof ObjectError) {
ObjectError objectError = (ObjectError) object;
System.out.println(objectError.getCode());
}
}
I hope it can be useful to you
我希望它对你有用
UPDATE
更新
If you want to get the message provided by your resource bundle, you need a registered messageSource instance (It mustbe called messageSource)
如果你想获取你的资源包提供的消息,你需要一个注册的messageSource实例(必须叫messageSource)
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="ValidationMessages"/>
</bean>
Inject your MessageSource instance inside your View
在您的视图中注入您的 MessageSource 实例
@Autowired
private MessageSource messageSource;
And to get your message, do as follows
要获取您的消息,请执行以下操作
for (Object object : bindingResult.getAllErrors()) {
if(object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
/**
* Use null as second parameter if you do not use i18n (internationalization)
*/
String message = messageSource.getMessage(fieldError, null);
}
}
Your Validator should looks like
你的验证器应该看起来像
/**
* Use null as fourth parameter if you do not want a default message
*/
errors.rejectValue("<FIELD_NAME_GOES_HERE>", "answerform.questionId.invalid", new Object [] {"123"}, null);
回答by Hoàng Long
I met this problem recently, and found an easier way (maybe it's the support of Spring 3)
最近遇到这个问题,找到了一个更简单的方法(可能是Spring 3的支持)
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
}
There's no need to change/add the message source.
无需更改/添加消息源。
回答by splashout
BEAN XML:
豆 XML:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
<bean id="messageAccessor" class="org.springframework.context.support.MessageSourceAccessor">
<constructor-arg index="0" ref="messageSource"/>
</bean>
JAVA:
爪哇:
for (FieldError error : errors.getFieldErrors()) {
logger.debug(messageAccessor.getMessage(error));
}
NOTE:Calling Errors.getDefaultMessage() will not necessarily return the same message that is generated from the code + args. The defaultMessage is a separate value defined when calling the Errors.rejectValue() method. See Errors.rejectValue() API Here
注意:调用 Errors.getDefaultMessage() 不一定会返回从代码 + args 生成的相同消息。defaultMessage 是调用 Errors.rejectValue() 方法时定义的单独值。请参阅此处的 Errors.rejectValue() API
回答by Krzysiek
With Java 8 Streams
使用 Java 8 流
bindingResult
.getFieldErrors()
.stream()
.forEach(f -> System.out.println(f.getField() + ": " + f.getDefaultMessage()));
回答by Valerii Starovoitov
WebMvcConfigurerAdapter:
WebMvcConfigurerAdapter:
@Bean(name = "messageSourceAccessor")
public org.springframework.context.support.MessageSourceAccessor messageSourceAccessor() {
return new MessageSourceAccessor( messageSource());
}
Controller:
控制器:
@Autowired
@Qualifier("messageSourceAccessor")
private MessageSourceAccessor messageSourceAccessor;
...
StringBuilder sb = new StringBuilder();
for (ObjectError error : result.getAllErrors()) {
if ( error instanceof FieldError) {
FieldError fe = (FieldError) error;
sb.append( fe.getField());
sb.append( ": ");
}
sb.append( messageSourceAccessor.getMessage( error));
sb.append( "<br />");
}