这几天在学着用spring mvc框架写页面,基于validation,感觉确实很方便.controller,validator都无需描述文件,只要打上@xxxxx.首次使用,边看demo边写代码.也碰到了些问题,比如在显示表单错误信息的时候,原先配置:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="errors">
这个class不能指定编码,页面乱码;查了一下资料后,改用ReloadableResourceBundleMessageSource,配置改成
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:basename="errors">
<!--property name="basename">
<value>errors</value>
</property-->
<property name="defaultEncoding" value="utf-8" />
</bean>
死活找不到资源文件,无奈只能debug,其实无须debug,看一下源代码也能找到原因
ResourceBundleMessageSource从classloader中加载资源文件,所以我一直帮资源文件打进jar包,没有问题,可以找到
ReloadableResourceBundleMessageSource加载时,默认使用DefaultResourceLoader,他会先判断资源path是否带有classpath:前缀,如果有,用ClassPathResource去加载资源文件,如果没有试着用文件协议的url去访问,再没有就在contextPath即WEB-INF下查找(这里还有一个问题,如果你的war包,没有被app server完全解开,那有可能访问不到).
于是我改配置为:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" p:basename="classpath:errors">
<!--property name="basename">
<value>errors</value>
</property-->
<property name="defaultEncoding" value="utf-8" />
</bean>
ok!