乱码分为多种情况,本文介绍两种常见的乱码现象和解决办法
1.@ResponseBody返回数据乱码
SpringMVC @ResponseBody默认情况下返回中文为乱码,原因是@ResponseBody采用的是
StringHttpMessageConverter
,而它采用的是ISO-8859-1编码。
//StringHttpMessageConverter 部分源码
/**
* Implementation of {@link HttpMessageConverter} that can read and write strings.
*
* <p>By default, this converter supports all media types ({@code */*}),
* and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
* by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
private final Charset defaultCharset;
private final List<Charset> availableCharsets;
private boolean writeAcceptCharset = true;
乱码问题有两种解决方案:
1.1局部解决方案
在@RequestMapping中声明produces
@ResponseBody
@RequestMapping(value = "/login",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
该方案只对已配置的请求生效,要全局生效需要采用方案二
1.2全局解决方案
在SpringMVC.xml中配置,可以从StringHttpMessageConverter源码中看出,需要配置supportedMediaTypes
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2.jsp传入参数乱码
2.1解决办法,在web.xml中加入编码过滤器
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>