後臺獲取ajax傳遞的參數, request.getParameter(“參數名”) 中文亂碼解決方法
原因:Http請求傳輸時將url以ISO-8859-1編碼,服務器收到字節流後默認會以ISO-8859-1編碼來解碼成字符流(造成中文亂碼)
解決辦法:我們需要把request.getParameter(“參數名”)獲取到的字符串先用ISO-8859-1編碼成字節流,然後再將其用utf-8解碼成字符流
我們可以通過轉碼的方式解決亂碼問題, 具體代碼如下:
String str= new String(request.getParameter("參數名").getBytes("iso-8859-1"), "utf-8");
ajax向後臺傳遞參數: (參數名爲name)
$.ajax({
url:'localhost:8080/test/test.do',
data: {'name': 'lili'}
});
後臺獲取參數:
1. 通過request獲取
@RequestMapping(value = "/test.do")
@ResponseBody
public Object selectAllDatas(HttpServletRequest request,HttpServletResponse response) {
try {
String(request.getParameter("參數名").getBytes("iso-8859-1"), "utf-8");
return null;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return null;
}
}
第二種: 直接獲取
@RequestMapping(value = "/test.do")
@ResponseBody
public Object selectAllDatas(String "參數名") {
try {
String("參數名".getBytes("iso-8859-1"), "utf-8");
return null;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return null;
}
}