How to get error text in controller from BindingResult

前端 未结 5 937
臣服心动
臣服心动 2020-12-01 01:58

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 conta

5条回答
  •  自闭症患者
    2020-12-01 02:49

    Disclaimer: I still do not use Spring-MVC 3.0

    But i think the same approach used by Spring 2.5 can fullfil your needs

    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 must be called messageSource)

    
        
    
    

    Inject your MessageSource instance inside your View

    @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("", "answerform.questionId.invalid", new Object [] {"123"}, null);
    

提交回复
热议问题