天天看點

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼ajax 亂碼SpringMVC亂碼tomcat亂碼idea編輯器亂碼一個小工具小結

使用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")
@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亂碼

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

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

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼ajax 亂碼SpringMVC亂碼tomcat亂碼idea編輯器亂碼一個小工具小結

idea編輯器亂碼

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

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

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼ajax 亂碼SpringMVC亂碼tomcat亂碼idea編輯器亂碼一個小工具小結

然後進入idea的安裝目錄D:\setup\IntelliJ IDEA 14.0.3\bin

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

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼ajax 亂碼SpringMVC亂碼tomcat亂碼idea編輯器亂碼一個小工具小結

可以使用Notepad++打開

解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼ajax 亂碼SpringMVC亂碼tomcat亂碼idea編輯器亂碼一個小工具小結

一個小工具

利用以下代碼輸出目前的編碼格式,如果輸出的是

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. 在idea\bin中idea.exe.vmoptions、idea64.exe.vmoptions添加 -Dfile.encoding=utf-8;

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

以上五條基本可以解決中文亂碼問題,有其他方法歡迎補充。

繼續閱讀