解決SpringMvc後台接收json資料中文亂碼問題的幾種方法,springmvcjson

來源:互聯網
上載者:User

解決SpringMvc後台接收json資料中文亂碼問題的幾種方法,springmvcjson

1、使用ajax從前台頁面傳輸資料到後台controller控制器的時候,出現中文亂碼(問號???)。

之前在網上找了各種解決方案,都行不通,最後發現是tomcat伺服器接收資料的問題

解決方案:

方式一:在controller接收參數時,對參數進行轉碼

@ResponseBody@RequestMapping(value="/getJsonDataByCityName",produces="application/json")public String getJsonByName(HttpServletRequest request,HttpServletResponse response,@RequestParam String city_name)throws ServletException,IOException{  //response.setContentType("text/html;charset=UTF-8");  //request.setCharacterEncoding("UTF-8");//解決post亂碼問題  System.out.println(request.getCharacterEncoding());  city_name = new String(city_name.getBytes("ISO-8859-1"), "UTF-8");  System.out.println("city_name:"+city_name);}

方式二:

配置tomcat目錄下的service.xml檔案

tomcat7/conf/server.xml

給該行代碼加上 URIEncoding="UTF-8" 的編碼屬性

<Connector port="8080" protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443" URIEncoding="UTF-8" />

原因分析:

其實亂碼問題出現的原因,就是由於預設的tomcat配置,接收請求是以ISO-8859-1來轉碼,導致中文出現了亂碼問題,只要能正確的以utf-8來轉碼,則可以解決亂碼問題。

2、普通資料轉送,從jsp頁面傳到後台controller,中文亂碼問題解決方案

(1)、首先檢查jsp頁面編碼格式是否是utf-8

(2)、設定中文過濾

<!-- 中文編碼 -->  <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>    <init-param>      <param-name>forceEncoding</param-name>      <param-value>true</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>characterEncodingFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

(3)、springMvc設定檔中設定JSON資料轉換

<mvc:annotation-driven>  <mvc:message-converters register-defaults="true">    <!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 註解請求映射    預設是ISO-88859-1,避免亂碼這裡設定為UTF-8 -->    <bean class="org.springframework.http.converter.StringHttpMessageConverter">      <property name="supportedMediaTypes" value="text/html;charset=UTF-8" />    </bean>    <!-- 啟動JSON格式的配置,自動將格式轉換成JSON格式,不需要其他類 -->    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">      <property name="supportedMediaTypes" value="application/json;charset=UTF-8" />    </bean>  </mvc:message-converters></mvc:annotation-driven>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.