36

我有一个返回 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 类只是一个 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...
}

调用 BindingResult.getAllErrors() 返回一个 FieldError 对象数组,但它没有实际错误。

4

6 回答 6

46

免责声明:我仍然不使用 Spring-MVC 3.0

但我认为 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());
    }
}

我希望它对你有用

更新

如果要获取资源包提供的消息,需要注册一个messageSource实例(必须叫messageSource)

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="ValidationMessages"/>
</bean>

在您的视图中注入您的 MessageSource 实例

@Autowired
private MessageSource messageSource;

要获取您的信息,请执行以下操作

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);
    }
}

你的验证器应该看起来像

/**
  * 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);
于 2010-05-02T04:14:18.673 回答
35

最近遇到这个问题,找到了更简单的方法(可能是Spring 3的支持)

    List<FieldError> errors = bindingResult.getFieldErrors();
    for (FieldError error : errors ) {
        System.out.println (error.getObjectName() + " - " + error.getDefaultMessage());
    }

无需更改/添加消息源。

于 2011-09-12T07:13:34.490 回答
14

使用 Java 8 流

bindingResult
.getFieldErrors()
.stream()
.forEach(f -> System.out.println(f.getField() + ": " + f.getDefaultMessage()));
于 2017-10-23T17:59:28.387 回答
2

豆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> 

爪哇:

for (FieldError error : errors.getFieldErrors()) {
    logger.debug(messageAccessor.getMessage(error));
}

注意:调用 Errors.getDefaultMessage() 不一定会返回从代码 + args 生成的相同消息。defaultMessage 是调用 Errors.rejectValue() 方法时定义的单独值。请参阅此处的 Errors.rejectValue() API

于 2013-12-12T17:51:03.797 回答
2

WebMvcConfigurerAdapter:

@Bean(name = "messageSourceAccessor")
public org.springframework.context.support.MessageSourceAccessor messageSourceAccessor() {
    return new MessageSourceAccessor( messageSource());
}

控制器:

@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 />");
}
于 2017-11-24T01:58:54.437 回答
1

To obtain a Map of all the errors associated with each field:

@Autowired
private MessageSource messageSource;

Map<String, List<String>> errorMap = bindingResult.getFieldErrors().stream()
    .collect(Collectors.groupingBy(FieldError::getField, 
    Collectors.mapping(e -> messageSource.getMessage(e, LocaleContextHolder.getLocale()), 
                        Collectors.toList())));
//In this example, each field/key is mapped to a 
//List of all the errors associated with that field

To obtain a Map with the errors associated with each field merged together as a single String:

@Autowired
private MessageSource messageSource;

Map<String, String> errorMap = bindingResult.getFieldErrors().stream()
        .collect(Collectors
                .toMap(FieldError::getField, 
                    e -> messageSource.getMessage(e, LocaleContextHolder.getLocale()), 
                    (a,b)->a + "<br/>" + b));
//In this example, multiple errors for the same field are separated with <br/>, 
//the line break element, to be easily displayed on the front end
于 2021-02-09T05:14:40.527 回答