您的位置:首頁技術文章
文章詳情頁

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

瀏覽:100日期:2023-09-24 17:25:25

使用idea進行JavaWeb開發時,在前端與后臺交互常常出現亂碼問題,包括日志/控制臺輸出亂碼,參數亂碼等問題,歸根結底是編碼格式不對,解決方法匯總如下。

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中添加以下代碼:

接收參數編碼設置:

comsumes='application/json;charset=UTF-8'

返回參數設置:

produces='application/json;charset=UTF-8'

完整代碼如下:

@RequestMapping(value = '/post', method = RequestMethod.POST,consumes='application/json;charset=UTF-8', produces='application/json;charset=UTF-8')@ResponseBodypublic 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亂碼

解決方法:進入idea->Run/Debug Configurations的tomcat->server設置,

在VM options添加 “-Dfile.encoding=utf-8”

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

設置tomcat編碼格式

idea編輯器亂碼

如果不是上述問題,那么中文亂碼可能是由編輯器引起的。

進入idea菜單 File->Setting-> File Encoding,將3標記的三處編碼改為”UTF-8”

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

設置idea編碼格式

然后進入idea的安裝目錄D:setupIntelliJ IDEA 14.0.3bin

idea.exe.vmoptions和idea64.exe.vmoptions兩個文件的末尾追加:’-Dfile.encoding=UTF-8’

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

可以使用Notepad++打開

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

一個小工具

利用以下代碼輸出當前的編碼格式,如果輸出的是GBK,則需要執行上面五個步驟,直到編碼輸出為UTF-8

System.out.println(System.getProperty('file.encoding'));

小結

解決亂碼問題的五大步驟(無先后順序):

1. ajax前端設置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. 在ideabin中idea.exe.vmoptions、idea64.exe.vmoptions添加 -Dfile.encoding=utf-8;

5. 在idea的設置中搜索“File Encoding”,把三個地方的編碼全部設置為uft-8

以上五條基本可以解決中文亂碼問題,有其他方法歡迎補充。這篇文章希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
国产综合久久一区二区三区