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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stloven5/article/details/53312012

话不多说,开门见山。


问题:

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

封装参数的POJO类

public class UserReqBean {

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

}

ValErrMsg.properties文件中的配置

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

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>

处理请求的Controller的代码和前端页面代码就不贴了,就是简单的读取错误信息回显。项目所有文件,包括properties文件,都是UTF-8的。但就是中文的错误信息出现乱码


解决:

经过潜(搜)心(索)研(谷)究(歌),发现问题就出现在spring-mvc.xml的配置。看起来貌似没有问题:

<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="UTF-8"/>

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

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

于是加上这个配置,就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();
    }

    return encoding1;
}

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

<!-- 资源文件编码格式 -->
<property name="fileEncodings" >
    <props>
        <prop key="classpath:ValErrMsg">UTF-8</prop>
    </props>
</property>

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


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

encoding = this.fileEncodings.getProperty(filename);

所以需要将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
不过获取文件编码那一段代码逻辑没变。

猜你喜欢

转载自blog.csdn.net/stloven5/article/details/53312012