Hibernate Validation and localized error messages?

故事扮演 提交于 2019-12-07 20:16:30

问题


hibernate and i want to provide localized error messages for hibernate annotations so i created to properties files ValidatorMessages.properties, ValidatorMessages_ar.properties

and put them in resources folder, and i am using messageSource to read from property files:

<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:messages</value>
                <value>classpath:errors</value>
                <value>classpath:app</value>
                <value>classpath:ValidatorMessages</value>
            </list>
        </property>
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

and in the class i use something like:

@NotNull(message = "{validation.notEmpty.password}")
private string password;

and when calling the validator i use:

Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();
        Set<ConstraintViolation<MyClass> cvs = validator
                .validate(myObject);
        for (ConstraintViolation<MyClass> cv : cvs) {
            String field = cv.getPropertyPath().toString();
            result.addError(new FieldError("version", field, cv.getMessage()));
        }

        if (result.hasErrors()) {
            initModel();
            result.reject("add.version.errors");
            return "manageVersions";
        }

it works fine with english, it displays english messages correctly, but when switching to arabic it still displays the english messages instead of arabic, although that

LocaleContextHolder.getLocale() indicates that the language is changed and it's arabic, so is there are something missing with the configuration or any ideas what might cause that ?


回答1:


In your Spring config when you are setting up your validator bean, I think you need to set the message interpolator:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="messageInterpolator" ref="interpolator" />
</bean>

where the interpolator bean would be of type LocaleContextMessageInterpolator (see here for more info). Hibernate Validator doesn't automatically know to look at LocaleContextHolder.

You might also need to set validationMessageSource property but I think its defaulted properly since you are at least getting the English error messages.



来源:https://stackoverflow.com/questions/5550065/hibernate-validation-and-localized-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!