文章目录
SpringMVC中解决乱码问题
1 中文乱码的原因
因为默认的字符集 ISO-8859-1 ,属于西欧字符集,只有数字,符号,英文,拉丁文…
所以解决乱码的核心就是将 ISO-8859-1 变成 UTF-8
2 乱码分类
2.1 请求乱码
1. GET请求乱码
如果你的Tomcat的版本比较高(Tomcat8.0及以上),则不会出现GET请求乱码
如果Tomcat版本比较低,如果再不更换版本的前提下,避免GET请求中中文乱码问题,则需要修改
Tomcat配置文件,在Tomcat安装目录的 conf 目录下
<Connector port="8080" protocol="HTTP/1.1"
URIEncoding="UTF-8"
connectionTimeout="20000"
redirectPort="8443" />
2. POST请求乱码
通过设置 过滤器
解决中文乱码问题
<filter>
<filter-name>character-filter</filter-name>
<filterclass>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>character-filter</filter-name>
<!--
/* 代表拦截所有请求,而且比/更彻底
eg: http://localhost:8080/index.jsp|index.css|index.js
/ 是不能拦截带后缀的请求的,而/* 可以
Struts 基于过滤器的 SpringMVC 基于Servlet
-->
<url-pattern>/*</url-pattern>
</filter-mapping>
2.2 响应乱码
绝大多数响应数据乱码,在SpringMVC中都加了 @ResponseBody
注解,而这个注解受
StringHttpMessageConverte
r 转换器的影响
1. 通常SpringMVC都会开启 注解开发模式
,所以绝大多数情况都是这么配置:
<!-- 开启SpringMVC的注解开发模式 -->
<!-- 这一个配置实际上包含两个组件: 1.处理器映射器: RequestMappingHandlerMapping
2. 处理器适配器: RequestMappingHandlerAdapter-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2. 也可以单独配置 HandlerAdapter
,实际不推荐使用,只是为了理解 Converter
和Adapter
的关系
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>