亂碼分為多種情況,本文介紹兩種常見的亂碼現(xiàn)象和解決辦法
1.@ResponseBody返回?cái)?shù)據(jù)亂碼
SpringMVC @ResponseBody默認(rèn)情況下返回中文為亂碼宫莱,原因是@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")
該方案只對(duì)已配置的請(qǐng)求生效授霸,要全局生效需要采用方案二
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傳入?yún)?shù)亂碼
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>