SpringMVC+HibernateValidator,配置在properties文件中的错误信息回显前端页面出现中文乱码

本文详细解析了在SpringMVC框架中使用Hibernate Validator进行参数校验时,中文错误信息显示乱码的问题及解决方案。通过调整ReloadableResourceBundleMessageSource的配置,正确设置资源文件编码,避免了乱码现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


问题:

后台在springMVC中使用hibernate-validator做参数校验的时候(validator具体使用方法见GOOGLE),用properties文件配置了校验失败的错误信息。发现回显给前端页面的时候中文错误信息显示乱码。

封装参数的POJO类

public class UserReqBean {

    @NotNull(message="{user.name.notnull}")
    private String userName;

}
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

ValErrMsg.properties文件中的配置

user.name.notnull=用户名不能为空
 
  • 1

spring-mvc.xml配置文件中validator的校验错误信息配置

<!-- 校验错误信息配置文件 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <!-- 资源文件名 -->
    <property name="basenames">
        <list>
            <value>classpath:ValErrMsg</value>
        </list>
    </property>
    <!-- 资源文件编码格式 -->
    <property name="fileEncodings" value="UTF-8"/>
    <!-- 对资源文件内容缓存时间,单位秒 -->
    <property name="cacheSeconds" value="120"/>
</bean>
 

    我根据网络上一篇讲springMVC+hibernateValidator的文章进行上面的配置,出现了中文乱码。
    后来搜到一篇提到过乱码,处理方式是Controller中获取错误信息从IOS-8895-1转UTF-8。但【鲁迅眉头一皱,发现事情并不靠谱.jpg】,框架出了这么久,怎么可能还存在这种需要自己手动转码的问题。
    再后来搜到一篇靠谱的文章,发现用的是这个配置:

    <property name="defaultEncoding" value="UTF-8"/>
     
    • 1

    于是加上这个配置,就OK了!!!


    原因:

    配置messageSource的时候,使用的是这个ReloadableResourceBundleMessageSource类,点进去看源码就发现问题在哪儿了。

    public class ReloadableResourceBundleMessageSource extends AbstractMessageSource implements ResourceLoaderAware {
    
        ···
    
        private String defaultEncoding;
        private Properties fileEncodings;
    
        ···
        }
    
    

    原来fileEncodings并不是个String类型,所以上面那个配置是错误的。再来看加载properties文件的方法(为了看得清楚点,我把写日志的部分删除了):

    protected Properties loadProperties(Resource resource, String filename) throws IOException {
        InputStream is = resource.getInputStream();
        Properties props = new Properties();
    
        Properties encoding1;
        try {
            if(resource.getFilename().endsWith(".xml")) {
    
                this.propertiesPersister.loadFromXml(props, is);
    
            } else {
    
                // 在这里读取properties文件
    
                String encoding = null;
                // 先从fileEncodings里面取编码方式(我之前的配置是String类型,这里就取不到编码)
                if(this.fileEncodings != null) {
                    encoding = this.fileEncodings.getProperty(filename);
                }
    
                // 没取到则直接使用defaultEncoding(汗!之前没配置!所以也没取到)
                if(encoding == null) {
                    encoding = this.defaultEncoding;
                }
    
                if(encoding != null) {
    
                    this.propertiesPersister.load(props, new InputStreamReader(is, encoding));
    
                } else {
    
                    // 取不到编码,就只能来这里咯
                    // 而InputStream默认的编码并不是UTF-8,而是ISO-8859-1
                    // 所以不管你怎么折腾都有问题,除非你愿意在所有地方手动转码
                    // is说:怪我咯!!
                    this.propertiesPersister.load(props, is);
                }
            }
    
            encoding1 = props;
        } finally {
            is.close();
        }
    
      
    
    

    弄清楚了原因,所以这里还有最正确的一种解决方案,xml配置如下:

    <!-- 资源文件编码格式 -->
    <property name="fileEncodings" >
        <props>
            <prop key="classpath:ValErrMsg">UTF-8</prop>
        </props>
    </property>
       
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这样就能正确设置fileEncodings这个配置项。


    再深入一点,fileEncodings是Properties类型,而Properties继承于HashTable。从前面加载文件的地方可以看到,取value的key用的是文件名filename。

    encoding = this.fileEncodings.getProperty(filename);
     
    • 1

    所以需要将prop标签的key设置为前面配置的文件名classpath:ValErrMsg(注意包含classpath)。同时也意味着如果有多个配置文件,可以对应资源文件列表为每个文件设置单独的编码。如果某个文件没有设置编码,就会使用defaultEncoding这个配置,如果没配置,就任由InputStream放荡不羁了……


    总结一下:
    1. 对于ReloadableResourceBundleMessageSource这个类,编码的正确设置方式是:为每个资源文件设置编码,并设置默认编码。当然,如果项目只会出现一种编码或者只有一个资源文件,可以直接简单粗暴的只设置一个defaultEncoding就行了。
    2. 网上的代码不一定跑得起来,遇到问题去网上搜索解决方案,不如自己先跟进源码去看。

    PS:小弟才疏学浅,还在努力的学习中,只是想记录下学习过程中遇到的问题。可能很简单的地方讲得很啰嗦还请多多包涵,另外许多疏漏之处还请斧正。


    更新

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

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值