spring thymeleaf中文乱码问题
分为request和response两种,然后可以设置字符集过滤或者字符集来解决。
request的过程
- request默认自带encoding
- Spring的CharacterEncodingFilter进行设置request的encoding
这样只要页面和后台保持一致,那么肯定不会乱码。这里主要就是为了解决很多浏览器即使在HTML页面设置了encoding,但request和reponse的时候还是不带字符集的问题。
response的过程
- 首先Spring对response进行字符集设置
- 读取template resource
- 使用viewResolver进行解析
解决方法:
设置request和response请求的字符集, 通过spring的EncodingFilter
<!-- spring character encoding filter --> <filter> <filter-name>springUtf8Encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>springUtf8Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
设置读取模板的encoding
<!-- template view --> <bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix" value=".html" /> <!-- HTML is the default value, added here for the sake of clarity. --> <property name="templateMode" value="HTML" /> <!-- Template cache is true by default. Set to false if you want --> <!-- templates to be automatically updated when modified. --> <property name="cacheable" value="false" /> <property name="characterEncoding" value="UTF-8" /> </bean>
设置视图解析的encoding
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <!-- NOTE 'order' and 'viewNames' are optional --> <property name="order" value="1" /> <property name="characterEncoding" value="UTF-8" /> <!--<property name="viewNames" value="*.html,*.xhtml" />--> </bean>
2017.05.22 update:
在使用restController的时候中文会默认显示iso-8859-1格式。
@requestmapping使用了RequestMappingHandlerAdapter来处理请求,对于@responsebody,当为string时,会调用默认构造方法里面add的StringHttpMessageConverter,需要注意的是,这个converter默认的编码是“ISO-8859-1”,所以需要重新定义StringHttpMessageConverter的字符集。
<!-- Message converter -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
<property name="writeAcceptCharset" value="true"/>
</bean>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</util:list>
</property>
</bean>