How to get error text in controller from BindingResult

前端 未结 5 883
臣服心动
臣服心动 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:38

    With Java 8 Streams

    bindingResult
    .getFieldErrors()
    .stream()
    .forEach(f -> System.out.println(f.getField() + ": " + f.getDefaultMessage()));
    
    0 讨论(0)
  • 2020-12-01 02:38

    BEAN 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

    0 讨论(0)
  • 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)

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

    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("<FIELD_NAME_GOES_HERE>", "answerform.questionId.invalid", new Object [] {"123"}, null);
    
    0 讨论(0)
  • 2020-12-01 02:52

    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 />");
    }
    
    0 讨论(0)
  • 2020-12-01 02:54

    I met this problem recently, and found an easier way (maybe it's the support of 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.

    0 讨论(0)
提交回复
热议问题