中國建設網(wǎng)站用戶名上海專業(yè)的seo公司
SpringMVC處理Ajax
參考文章數(shù)據(jù)交換的常見格式,如JSON格式和XML格式
請求參數(shù)的攜帶方式
瀏覽器發(fā)送到服務器的請求參數(shù)有name=value&...(鍵值對)
和{key:value,...}(json對象)
兩種格式
URL請求
會將請求參數(shù)以鍵值對的格式拼接到請求地址后面,form表單的GET和POST請求
會將請求參數(shù)以鍵值對的格式存儲到請求報文的請求體中- 發(fā)起Ajax請求時,可以將請求參數(shù)以Json的格式存儲到請求報文的請求體中
控制器方法獲取兩種格式請求參數(shù)的方式
- 以
name=value&
鍵值對格式發(fā)送到服務器的請求參數(shù)的可以通過request對象的API獲取,即在SpringMVC中可以直接通過控制器方法的形參獲取請求參數(shù) - 以
{key:value,}
Json格式的請求參數(shù)時無法通過request對象獲取,在SpringMVC中需要使用@RequestBody
注解標識控制器方法的形參獲取請求參數(shù)
發(fā)起Ajax請求的方式
現(xiàn)在比較流行的開發(fā)方式為異步調(diào)用, 前后臺以異步Ajax請求的方式進行交換數(shù)據(jù),傳輸?shù)臄?shù)據(jù)使用的是JSON
- Ajax請求發(fā)送后,當瀏覽器接收到服務器的響應內(nèi)容后不會重新加載整個頁面,只會更新網(wǎng)頁的部分實現(xiàn)局部刷新的效果
使用vue.js
提供的axios
方法發(fā)起Ajax請求,方法的參數(shù)是一個配置對象
method
: 指定請求的方式url
: 指定請求的路徑params
和data
: 指定請求的參數(shù)
params
和data
屬性的區(qū)別
- 使用params屬性時無論發(fā)送GET還是POST請求,請求參數(shù)都是以
name=value&name=value
的格式拼接到請求地址后,獲取請求參數(shù)時通過requset對象的API - 使用data屬性時,只能發(fā)送POST請求,請求參數(shù)是以
json的格式
存儲到請求報文的請求體中,獲取請求參數(shù)時需要相關的jar包將請求體中的json數(shù)據(jù)轉成Java對象
使用axios({配置對象})
方法發(fā)起Ajax請求,使用params屬性
將請求參數(shù)以name=value&name=value
的格式拼接到請求地址后
testAjax:function (event) {axios({method:"post",url:event.target.href,params:{username:"admin",password:"123456"}}).then(function (response) {//服務器處理Ajax請求成功后執(zhí)行的回調(diào)函數(shù)// 服務器響應的結果都會被封裝在response對象中,響應的數(shù)據(jù)都在data屬性中alert(response.data);});
使用axios.post(url,[data])
方法和axios.get(url)
方法發(fā)起Ajax請求,使用data屬性
將請求參數(shù)以json的格式
存儲到請求報文的請求體中
testAjax(){axios.post("/SpringMVC/test/ajax",{username:"admin",password:"123456"}).then(response=>{console.log(response.data);});
},
處理鍵值對的請求參數(shù)
使用axios({配置對象})
方法發(fā)起Ajax請求,使用params屬性
將請求參數(shù)以name=value&name=value
的格式拼接到請求地址后
<div id="app"><!--請求超鏈接--><a @click="testAxios()" th:href="@{/testAxios}">SpringMVC處理ajax</a>
</div>
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
<script type="text/javascript">var vue = new Vue({el:"#app",methods:{testAjax:function (event) {axios({method:"post",url:event.target.href,params:{username:"admin",password:"123456"}}).then(function (response) {//服務器處理Ajax請求成功后執(zhí)行的回調(diào)函數(shù)// 服務器響應的結果都會被封裝在response對象中,響應的數(shù)據(jù)都在data屬性中alert(response.data);});// 阻止超鏈接默認的跳轉行為event.preventDefault();}}});
</script>
編寫控制器方法處理瀏覽器發(fā)起的Ajax請求,直接在控制器方法中的聲明同名的形參獲取請求地址中的請求參數(shù)
@RequestMapping("/testAxios")
public void testAxios(String username, String password,HttpServletResponse response){System.out.println("username:"+username+",password:"+password);// 由于我們發(fā)起的是Ajax請求就是用來做局部刷新的即頁面不能跳轉,所以不能直接返回視圖名稱轉發(fā)或重定向到一個頁面,而是響應數(shù)據(jù)response.getWriter().write("hello,axios");
}
@RequestBody注解處理json格式
使用axios.post(url,[data])
方法和axios.get(url)
方法發(fā)起Ajax請求,將請求參數(shù)以json的格式
存儲到請求報文的請求體中
testAjax(){axios.post("/SpringMVC/test/ajax",{username:"admin",password:"123456"}).then(response=>{console.log(response.data);});
},testRequestBody(){axios.post("/SpringMVC/test/RequestBody/json",{username:"admin",password:"123456",age:23,gender:"男"}).then(response=>{console.log(response.data);});
},
@RequestBody
注解可以用來標識控制器方法的形參, 默認可以獲取當前請求的請求體的全部內(nèi)容然后為注解所標識的String類型的形參
賦值
- 將請求中請求體所包含的數(shù)據(jù)傳遞給請求參數(shù),此注解一個處理器方法只能使用一次
@RequestMapping("test/ajax")
public void testRequestBody(@RequestBody String requestBody){// requestBody:{"username":"admin","password":"123456"}System.out.println("requestBody:"+requestBody);// 由于我們發(fā)起的是Ajax請求就是用來做局部刷新的即頁面不能跳轉,所以不能直接返回視圖名稱轉發(fā)或重定向到一個頁面,而是響應數(shù)據(jù)response.getWriter().write("hello,axios");
}
需求: 使用@RequestBody注解
獲取請求體中json格式的請求參數(shù),并且將json格式的請求參數(shù)轉化為指定類型的Java對象或Map集合
第一步: 導入jackson
的依賴
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.1</version>
</dependency>
第二步: 在SpringMVC的配置文件中開啟mvc的注解驅(qū)動
<!--開啟mvc注解驅(qū)動-->
<mvc:annotation-driven />
第三步: 指定實體類用來封裝請求體中json格式的請求參數(shù)
public class User {private Integer id;private String username;private String password;private Integer age;private String gender;public User() {}public User(Integer id, String username, String password, Integer age, String gender) {this.id = id;this.username = username;this.password = password;this.age = age;this.gender = gender;}//getter和setter以及toString方法
}
第四步: 發(fā)起POST請求方式的Ajax請求,將請求參數(shù)以json的格式存儲到請求報文的請求體中,然后傳輸?shù)椒掌?/strong>
testRequestBody(){axios.post("/SpringMVC/test/RequestBody/json",{username:"admin",password:"123456",age:23,gender:"男"}).then(response=>{console.log(response.data);});
},
第五步: 使用@RequestBody注解
獲取請求體中json格式的請求參數(shù)然后轉化為指定的實體類對象或Map集合
// 將請求體中json格式的數(shù)據(jù)轉換為map集合
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody Map<String, Object> map,HttpServletResponse response) throws IOException {//{username=admin, password=123456,age=23,gender=男}System.out.println(map);response.getWriter().print("hello,axios");
}// 將請求體中json格式的數(shù)據(jù)轉換為User對象
@RequestMapping("/test/RequestBody/json")
public void testRequestBody(@RequestBody User user, HttpServletResponse response) throws IOException {//User{id=null, username='admin', password='123456', age=null,gender='null'}System.out.println(user);response.getWriter().print("hello,axios");
}
JSON格式的擴展
控制器方法參數(shù)前添加@RequestBody
注解,將請求體中的Json數(shù)組映射到List集合類型形參的String類型對象中
@RequestMapping("/jsonArrayParam")@ResponseBodypublic String jsonArrayParam(@RequestBody List<String> hobbies) {// JSON數(shù)組參數(shù)傳遞hobbies --> [唱, 跳, Rap, 籃球]System.out.println("JSON數(shù)組參數(shù)傳遞hobbies --> " + hobbies);return "{'module':'json array param'}";}
將請求體中的嵌套的Json對象數(shù)據(jù)
映射到POJO對象形參的屬性中
{"name":"菲茨羅伊","age":"27","address":{"city":"薩爾沃", "province":"外域"}}
@RequestMapping("/jsonPojoParam")
@ResponseBody
public String jsonPojoParam(@RequestBody User user) {// User{name=’菲茨羅伊’, age=27, address=Address{province=’外域’, city=’薩爾沃’}}System.out.println("JSON對象參數(shù)傳遞user --> " + user);return "{'module':'json pojo param'}";
}
將請求體中包含JSON對象的數(shù)組
映射到集合形參的多個POJO對象屬性中
[{"name":"菲茨羅伊","age":"27","address":{"city":"薩爾沃","province":"外域"}},{"name":"地平線","age":"136","address":{"city":"奧林匹斯","province":"外域"}}
]
@RequestMapping("/jsonPojoListParam")
@ResponseBody
public String jsonPojoListParam(@RequestBody List<User> users) {/*user —> [User{name=’菲茨羅伊’, age=27, address=Address{province=’外域’, city=’薩爾沃’}},User{name=’地平線’, age=136, address=Address{province=’外域’, city=’奧林匹斯’}}]*/System.out.println("JSON對象數(shù)組參數(shù)傳遞user --> " + users);return "{'module':'json pojo list param'}";
}