溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringMVC中的json數(shù)據(jù)怎么利用controller進行接收

發(fā)布時間:2020-12-05 16:09:08 來源:億速云 閱讀:212 作者:Leah 欄目:編程語言

SpringMVC中的json數(shù)據(jù)怎么利用controller進行接收?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

1.jsp頁面發(fā)送ajax的post請求:

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("請求失敗");
    }
  })
}

注意:

1.在發(fā)送數(shù)據(jù)時,data鍵的值一定要寫成JSON.stringify(json),將數(shù)據(jù)轉(zhuǎn)換成json格式,否則會拋出異常

2.basePath是項目根目錄:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

2.controller接收請求:

  @ResponseBody
  @RequestMapping(value="/ajaxRequest",method=RequestMethod.POST)
  public User ajaxRequest(@RequestBody User user){
    System.out.println(user);
    return user;
  }

注意:

1.@ResponseBody修飾的方法返回的數(shù)據(jù),springmvc將其自動轉(zhuǎn)換成json格式,然后返回給前端

2.@RequestBody修飾目標(biāo)方法的入?yún)ⅲ梢詫jax發(fā)送的json對象賦值給入?yún)?。?dāng)然這里的入?yún)ser是我們自定義的實體類型。

3.最后將user返回,springmvc自動將其轉(zhuǎn)換成json返回給前端

關(guān)于SpringMVC中的json數(shù)據(jù)怎么利用controller進行接收問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI