SpringMVC中controller接收json數(shù)據(jù)的方法
本文實(shí)例為大家分享了SpringMVC中controller接收json數(shù)據(jù)的方法,供大家參考,具體內(nèi)容如下
1.jsp頁(yè)面發(fā)送ajax的post請(qǐng)求:
function postJson(){
var json = {"username" : "imp", "password" : "123456"};
$.ajax({
type : "post",
url : "<%=basePath %>ajaxRequest",
contentType : "application/json;charset=utf-8",
dataType : "json",
data: JSON.stringify(json),
success : function(data){
alert("username:"+data.username+" id:"+data.id);
},
error : function(){
alert("請(qǐng)求失敗");
}
})
}
注意:
1.在發(fā)送數(shù)據(jù)時(shí),data鍵的值一定要寫(xiě)成JSON.stringify(json),將數(shù)據(jù)轉(zhuǎn)換成json格式,否則會(huì)拋出異常
2.basePath是項(xiàng)目根目錄:
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
2.controller接收請(qǐng)求:
@ResponseBody
@RequestMapping(value="/ajaxRequest",method=RequestMethod.POST)
public User ajaxRequest(@RequestBody User user){
System.out.println(user);
return user;
}
注意:
1.@ResponseBody修飾的方法返回的數(shù)據(jù),springmvc將其自動(dòng)轉(zhuǎn)換成json格式,然后返回給前端
2.@RequestBody修飾目標(biāo)方法的入?yún)ⅲ梢詫jax發(fā)送的json對(duì)象賦值給入?yún)?。?dāng)然這里的入?yún)ser是我們自定義的實(shí)體類(lèi)型。
3.最后將user返回,springmvc自動(dòng)將其轉(zhuǎn)換成json返回給前端
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java開(kāi)發(fā)Dubbo注解Adaptive實(shí)現(xiàn)原理
這篇文章主要為大家介紹了java開(kāi)發(fā)Dubbo注解Adaptive實(shí)現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Java HashSet(散列集),HashMap(散列映射)的簡(jiǎn)單介紹
這篇文章主要介紹了Java HashSet(散列集),HashMap(散列映射)的簡(jiǎn)單介紹,幫助大家更好的理解和學(xué)習(xí)Java集合框架的相關(guān)知識(shí),感興趣的朋友可以了解下2021-01-01
Spring Cloud Feign實(shí)現(xiàn)動(dòng)態(tài)URL
本文主要介紹了Spring Cloud Feign實(shí)現(xiàn)動(dòng)態(tài)URL,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
java 數(shù)值類(lèi)型分秒時(shí)間格式化的實(shí)例代碼
這篇文章主要介紹了java 數(shù)值類(lèi)型分秒時(shí)間格式化的實(shí)例代碼的相關(guān)資料,將秒或分鐘的值轉(zhuǎn)換為xx天xx小時(shí)xx分鐘xx秒 如果 “xx” 為0 自動(dòng)缺省,需要的朋友可以參考下2017-07-07

