SpringMVC 通過ajax 前后端數(shù)據(jù)交互的實現(xiàn)方法
在前端的開發(fā)過程中,經(jīng)常在html頁面通過ajax進(jìn)行前后端數(shù)據(jù)的交互,SpringMVC的controller進(jìn)行數(shù)據(jù)的接收,但是有的時候后端會出現(xiàn)數(shù)據(jù)無法接收到的情況,這個是因為我們的參數(shù)和前端ajax的contentType參數(shù) 類型不對應(yīng)的情景,或者說contentType和后臺controller 方法參數(shù)到底存在什么樣的關(guān)系
普通的參數(shù)我們傳遞的時候往往是這樣的兩種情況:
contentType: "application/x-www-form-urlencoded",
contentType: "application/json",
這樣的兩種方式有什么樣的區(qū)別,
第一種方式:application/x-www-form-urlencoded 參數(shù)會解析為參數(shù)表,比如:
name=John+Doe&age=30&city=New+York
通過ajax 傳遞,ajax寫法如下:
let params={
"username":"張三",
"password":"123456",
}
$.ajax({
url: "dologin4",
contentType: "application/x-www-form-urlencoded",
headers: { 'Authorization': "****",'Access-Control-Allow-Origin':'*'},
type: 'post',
data: params,
success: function(result) {
console.log(result)
},
error: function(data) {
console.log('接口不通');
}
});這樣的形式,后臺接受的時候,使用:request.getParameter()或@RequestParam,比如:
@RequestMapping("/dologin")
public ModelAndView dologin(@RequestParam String username,@RequestParam String password) throws Exception {
System.out.println(username);
System.out.println(password);
ModelAndView mav = new ModelAndView();
mav.addObject("info", "歡迎你");
mav.setViewName("success");
return mav;
}
@ResponseBody
@RequestMapping("/dologin2")
public Map<String,Object> dologin2(HttpServletRequest request,HttpServletResponse response) throws Exception {
String username=request.getParameter("username");
System.out.println(username);
Map<String,Object> map=new HashMap<>();
map.put("aa", "1111");
return map;
}適合 x-www-form-urlencoded 的情況:
- 傳統(tǒng)HTML表單提交
- 簡單的鍵值對數(shù)據(jù)
- 需要向后兼容老系統(tǒng)
- 文件上傳(結(jié)合
multipart/form-data)
第二種方式:contentType: "application/json", 整個body作為單一數(shù)據(jù)流處理,比如:
{
"name": "John Doe",
"age": 30,
"city": "New York",
"hobbies": ["reading", "swimming"]
}通過ajax 傳遞,ajax寫法如下:
function dologin(){
let params={
"username":"張三",
"password":"123456",
}
$.ajax({
url: "dologin4",
contentType: "application/json",
headers: { 'Authorization': "****",'Access-Control-Allow-Origin':'*'},
type: 'post',
data: JSON.stringify(params),
success: function(result) {
console.log(result)
},
error: function(data) {
console.log('接口不通');
}
});
}Java后臺接受前臺傳入?yún)?shù)的代碼如下:@RequestBody
@ResponseBody
@RequestMapping("/dologin4")
public Map<String,Object> dologin4(HttpServletRequest request,HttpServletResponse response) throws Exception {
String uu=request.getParameter("username");
System.out.println(uu);
StringBuilder jsonBuilder = new StringBuilder();
try (BufferedReader reader = request.getReader()) {
String line;
while ((line = reader.readLine()) != null) {
jsonBuilder.append(line);
}
}
String jsonString = jsonBuilder.toString();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(jsonString, Map.class);
String username = (String) jsonMap.get("username");
System.out.println(username);
Map<String,Object> map=new HashMap<>();
map.put("aa", "1111");
return map;
}
@ResponseBody
@RequestMapping("/dologin3")
public Map<String,Object> dologin3(@RequestBody Map<String,Object> reqMap) throws Exception {
String username=reqMap.get("username").toString();
System.out.println(username);
Map<String,Object> map=new HashMap<>();
map.put("aa", "1111");
return map;
}適合 application/json 的情況:
- RESTful API通信
- 復(fù)雜數(shù)據(jù)結(jié)構(gòu)
- 需要明確數(shù)據(jù)類型
- 前后端分離架構(gòu)
- 移動應(yīng)用與服務(wù)器通信
兩種情景是不一樣的,如果你前端傳入的是json格式,那么后端你用:
String uu=request.getParameter("username");
System.out.println(uu);這樣是無法接收到數(shù)據(jù)的,接收到的參數(shù)一直為null,因為json是整體作為一個流傳入到后臺的
相關(guān)文章
Java中你真的會用Constructor構(gòu)造器嗎之看完本篇你就真的會了
顯式初始化要求我們在寫程序時就確定初始值,這有時很不方便。我們可以使用構(gòu)造器(constructor)來初始化對象。構(gòu)造器可以初始化數(shù)據(jù)成員,還可以規(guī)定特定的操作。這些操作會在創(chuàng)建對象時自動執(zhí)行。下面文字將對該內(nèi)容做詳細(xì)介紹,需要的小伙伴請參考2021-09-09
java中volatile和synchronized的區(qū)別與聯(lián)系
這篇文章主要介紹了java中volatile和synchronized的區(qū)別與聯(lián)系的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解這部分內(nèi)容,需要的朋友可以參考下2017-10-10
mybatis中關(guān)于mapper的使用以及注意事項
這篇文章主要介紹了mybatis中關(guān)于mapper的使用以及注意事項,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
妙用Java8中的Function接口消滅if...else
在開發(fā)過程中經(jīng)常會使用if...else...進(jìn)行判斷拋出異常、分支處理等操作。這些if...else...充斥在代碼中嚴(yán)重影響了代碼代碼的美觀,本文就妙用Java8中的Function接口消滅if...else,感興趣的可以了解一下2022-01-01

