2015-12-21 49 views
0

我的項目使用spring mvc和hibernate驗證程序。並且我試圖讓它支持多語言。 這是我的春天的i18n文件Hibernate驗證程序無法通過鍵獲取值

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 

    <mvc:interceptors> 
     <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> 
      <property name="paramName" value="lang"/> 
     </bean> 
    </mvc:interceptors> 


    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> 
     <property name="cookieMaxAge" value="604800"/> 
     <property name="defaultLocale" value="zh_CN" /> 
     <property name="cookieName" value="language"></property> 
    </bean> 

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
     <property name="basenames"> 
      <list> 
       <value>classpath:i18N/messages</value> 
       <value>classpath:i18N/validation</value> 
      </list> 
     </property> 
      <property name="defaultEncoding" value="UTF-8" /> 
     <property name="useCodeAsDefaultMessage" value="false"/> 
    </bean> 

    <mvc:annotation-driven validator="validator" /> 

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
     <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> 
     <property name="validationMessageSource" ref="messageSource"/> 
    </bean> 
</beans> 

而且我的問題是,當我使用標註在Bean文件,這樣,

@Size(min=6, max=25,message="{password_length_require}") 
private String password; 

,並在validation_en_US.properties,我這樣做

password_length_require=The password length require more than 5 and less 25 

結果是該頁面將輸出「{password_length_require}」。 在另一方面,在我的控制,我用

bindingResult.rejectValue("password", "password_length_require"); 

它會正常工作......

任何人可以幫助我嗎?

回答

0

我以前遇到同樣的問題,花了很長時間才解決。 就像我一樣,以下配置可能有問題。

<property name="basenames"> 
     <list> 
      <value>classpath:i18N/messages</value> 
      <value>classpath:i18N/validation</value> 
     </list> 
    </property> 

的財產「基本名稱」的值必須是完整路徑的驗證消息的文件保存在您的project.For例如,如果驗證消息的文件是在一個名爲包「org.example.config.i18N.messages」 ,你應該像這樣配置xml:

<value>classpath:org/example/config/i18N/messages</value> 

所以也許你需要檢查你的配置是否正確。 以上是我的經驗,希望對你有所幫助。