简体   繁体   中英

Using ValidationMessages bundle with Spring Webflow Validation?

How do I wire up a Spring ValidationMessages bundle in a custom Webflow Validator class? I have a validator implemented and working:

public void validateBusinessReferences(BusinessReferencesViewDao businessReferences, Errors errors) {
    if (somecondition())) {
        errors.rejectValue("name", "validation.message123", "This field is bad.");
    }
}

But instead of the message from the ValidationMessages.properties file, I get the fallback default of This field is bad.

All my other messages and validations work fine - it's just this custom validator/custom message scenario that's failing. I suspect a Spring configuration problem of some kind but I can't isolate it.

My understanding is that the ValidationMessages.properties is for customizing messages when using JSR-303 style annotations. Since your're not using those here - rather you're using a custom validator method and calling errors.rejectValue directly, you should place your messages in the standard messages.properties file. In webflow, this file is flow specific and lives alongside the flow definition XML file in the same folder.

Problem solved - I was missing a step. In order to use a properties bundle you need to use a MessageResolver and call it like so:

MessageResolver messageResolver = new MessageBuilder().error().source(source).code("validation.message.property.here").defaultText(errorMessage).build();
messageResolver.resolveMessage(messageSource, Locale.ENGLISH);
return messageResolver;

Where your messageSource is your Spring bean with your message properties bundles, defined in your application context:

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

Documentation on MessageResolver is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM