您的位置:首页 > 编程语言 > Java开发

阅读Spring in action 实现书中实例时遇到的问题(三)之解决 JSR303校验获取ValidationMessage.properties错误信息文件的中文乱码问题

2018-11-26 10:10 991 查看

使用 ValidationMessage.properties配置错误信息,前端jsp页面回显错误提示信息时总是乱码,网上查了好久,最后还是下面的代码靠谱

在springmvc-config.xml中添加以下配置

[code]<!-- 加载属性文件 -->
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件名 -->
<property name="basenames">
<list>
<value>classpath:ValidationMessage</value>
</list>
</property>
<!-- 解决 ValidationMessage.properties错误信息文件的中文乱码问题 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean>
[code]<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<property name="validationMessageSource" ref="messageSource" />
</bean>

上面这段代码特别划重点,必须要加!

下面给出基于javaconfig配置的webconfig代码

[code]//加载属性文件
@Override
public Validator getValidator() {
return validator();
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource=new ReloadableResourceBundleMessageSource();
messageSource.setDefaultEncoding("utf-8");
messageSource.setBasename("classpath:ValidationMessage");
return messageSource;
}
//配置校验错误信息配置
@Bean
public Validator validator() {
LocalValidatorFactoryBean validator=new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}

更新(原文:https://blog.csdn.net/stloven5/article/details/53312012 

之前使用的是springmvc版本4.1.1.RELEASE,ReloadableResourceBundleMessageSource类直接继承于AbstractMessageSource。大概是在4.2以后的版本中,抽象出一个新类:AbstractResourceBasedMessageSource,defaultEncoding属性放到了抽象类中。 
继承关系从 
ReloadableResourceBundleMessageSource –> AbstractMessageSource 
变成了ReloadableResourceBundleMessageSource –> AbstractResourceBasedMessageSource –> AbstractMessageSource 
不过获取文件编码那一段代码逻辑没变。
 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐