解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題
使用idea進(jìn)行JavaWeb開發(fā)時,在前端與后臺交互常常出現(xiàn)亂碼問題,包括日志/控制臺輸出亂碼,參數(shù)亂碼等問題,歸根結(jié)底是編碼格式不對,解決方法匯總?cè)缦隆?/p>
ajax 亂碼
解決方法:在contentType中添加”charset=utf-8”
$.ajax({
url:"/rest/get",
type:"POST",
contentType:"application/json;charset=utf-8", //添加編碼格式
data:JSON.stringify(a),
dataType:"json",
success:function(data){
console.log("success!");
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus);
console.log(errorThrown);
}
});
SpringMVC亂碼
解決方法:在@RequestMapping中添加以下代碼:
接收參數(shù)編碼設(shè)置:
comsumes="application/json;charset=UTF-8"
返回參數(shù)設(shè)置:
produces="application/json;charset=UTF-8"
完整代碼如下:
@RequestMapping(value = "/post", method = RequestMethod.POST,consumes="application/json;charset=UTF-8", produces="application/json;charset=UTF-8")
@ResponseBody
public String getDailyLog(@RequestBody String message){
System.out.println("編碼格式為: "+System.getProperty("file.encoding"));
System.out.println("message: "+message);
logger.info(dailyLogShowService.getContent());
System.out.println("System.out + "+"中文:"+dailyLogShowService.getContent());
DailyLog dailyLog = dailyLogShowService.getDailyLog();
logger.info(dailyLog);
return "{\"a\":\"返回中文\"}";
}
tomcat亂碼
解決方法:進(jìn)入idea->Run/Debug Configurations的tomcat->server設(shè)置,
在VM options添加 “-Dfile.encoding=utf-8”

設(shè)置tomcat編碼格式
idea編輯器亂碼
如果不是上述問題,那么中文亂碼可能是由編輯器引起的。
進(jìn)入idea菜單 File->Setting-> File Encoding,將3標(biāo)記的三處編碼改為”UTF-8”

設(shè)置idea編碼格式
然后進(jìn)入idea的安裝目錄D:\setup\IntelliJ IDEA 14.0.3\bin
idea.exe.vmoptions和idea64.exe.vmoptions兩個文件的末尾追加:'-Dfile.encoding=UTF-8'

可以使用Notepad++打開

一個小工具
利用以下代碼輸出當(dāng)前的編碼格式,如果輸出的是GBK,則需要執(zhí)行上面五個步驟,直到編碼輸出為UTF-8
System.out.println(System.getProperty("file.encoding"));
小結(jié)
解決亂碼問題的五大步驟(無先后順序):
1. ajax前端設(shè)置application/json;charset=utf-8;
2. springmvc后臺添加 consumes = “application/json;charset=utf-8”, produces = “application/json;charset=utf-8”;
3. 在tomcat->server->vmoption中加入-Dfile.encoding=utf-8;
4. 在idea\bin中idea.exe.vmoptions、idea64.exe.vmoptions添加 -Dfile.encoding=utf-8;
5. 在idea的設(shè)置中搜索“File Encoding”,把三個地方的編碼全部設(shè)置為uft-8
以上五條基本可以解決中文亂碼問題,有其他方法歡迎補(bǔ)充。這篇文章希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
深入理解Java定時調(diào)度(Timer)機(jī)制
這篇文章主要介紹了深入理解Java定時調(diào)度(Timer)機(jī)制,本節(jié)我們主要分析 Timer 的功能。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
Jenkins遷移job插件Job Import Plugin流程詳解
這篇文章主要介紹了Jenkins遷移job插件Job Import Plugin流程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
JDK動態(tài)代理,代理接口沒有實(shí)現(xiàn)類,實(shí)現(xiàn)動態(tài)代理方式
這篇文章主要介紹了JDK動態(tài)代理,代理接口沒有實(shí)現(xiàn)類,實(shí)現(xiàn)動態(tài)代理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Android開發(fā)在輪播圖片上加入點(diǎn)擊事件的方法
這篇文章主要介紹了Android開發(fā)在輪播圖片上加入點(diǎn)擊事件的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11

