SpringMVC 學習-返回字符串中文亂碼問題解決

1、使用 SpringMVC 框架時,若是 HTTP 請求資源返回的是中文字符串,則會出現亂碼。緣由以下:html

SpringMVC 框架能夠使用 @RequestBody 和 @ResponseBody 兩個註解,分別完成請求到對象和對象到響應的轉換,底層這種靈活的響應機制,就是Spring3.X 新引入的 HttpMessageConverter 即消息轉換器機制。該機制默認的編碼爲 ISO-8859-1app

源碼以下:框架

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

 

2、那這種狀況該怎麼解決呢post

經本人測試有效的解決辦法,有以下兩個:測試

1. 在 @RequestMapping 裏面加入 produces="text/html;charset=UTF-8"編碼

@ResponseBody
@RequestMapping(value="/logon",produces="text/html; charset=UTF-8")
public String logon(){
}

這種方式的不足之處在於,咱們的每一個 controller 都須要這麼配置,算是比較麻煩。spa

 

那還有其餘省事的、一勞永逸的辦法嗎?有的。code

 

2. 使用 Spring 的後置處理器 BeanPostProcessorhtm

對這個類不太瞭解的,見:http://www.cnblogs.com/libra0920/p/6118157.html 有一個簡單的說明。對象

在 bean 實例化以後,當 bean 的類型爲 StringHttpMessageConverter 時,設置 @responseBody 返回數據編碼爲 utf8 格式。

/**
 * 實例化以後進行處理
 */
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  if(bean instanceof StringHttpMessageConverter){
    MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8"));
    List<MediaType> types = new ArrayList<MediaType>();
    types.add(mediaType);
    ((StringHttpMessageConverter) bean).setSupportedMediaTypes(types);
  }
  return bean;
}

以上。

擺脫亂碼困擾。

相關文章
相關標籤/搜索