SpringMVC-表單序列化、@RequestBody

SpringMVC-表單序列化、@RequestBody

序列化轉 json

這樣使用的目的就是能夠減輕代碼量,可以不通過表單中的name一個一個的通過拼接來發送數據

(function($){
          $.fn.serializeJson=function(){
              var serializeObj={};
              var array=this.serializeArray();
              var str=this.serialize();
              $(array).each(function(){
                  if(serializeObj[this.name]){
                      if($.isArray(serializeObj[this.name])){
                          serializeObj[this.name].push(this.value);
                      }else{
                          serializeObj[this.name]=[serializeObj[this.name],this.value];
                      }
                  }else{
                      serializeObj[this.name]=this.value;
                  }
              });
              return serializeObj;
          };
      })(jQuery);

@RequestBoby

作用:

1.默認情況下我們發送的都是Content-Type: application/x-www-form-urlencoded,直接使用@RequestParam接收參數。

2.如果不是Content-Type:application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等,要使用@RequestBody接收參數,不然會出錯。

代碼示例:

前端發送界面:

<%--
  Created by IntelliJ IDEA.
  User: Dell
  Date: 2019/10/5
  Time: 16:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.4.1.js"></script>
  </head>
  <body>
  <form id="myform">
    user:<input type="text" name="username"><br>
    age:<input type="text" name="age" ><br>
    愛好:<input type="checkbox" name="hobby" value="籃球"> 籃球
    <input type="checkbox" name="hobby" value="乒乓球"> 乒乓球
    <input type="checkbox" name="hobby" value="足球"> 足球
  </form>
  <input type="button" id="formbtn" value="發送form">

  <script>
  $(function () {
      //表單序列化 轉json
    (function($){
      $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();
        $(array).each(function(){
          if(serializeObj[this.name]){
            if($.isArray(serializeObj[this.name])){
              serializeObj[this.name].push(this.value);
            }else{
              serializeObj[this.name]=[serializeObj[this.name],this.value];
            }
          }else{
            serializeObj[this.name]=this.value;
          }
        });
        return serializeObj;
      };
    })(jQuery);


    $('#formbtn').click(function () {
      //獲取表單中的所有數據
      /*var serialize = $('#myform').serialize();
      console.log(serialize);*/
      /*輸出的數據格式爲:username=%E4%BD%95%E9%BE%99&age=12&hobby=%E7%AF%AE%E7%90%83&hobby=%E4%B9%92%E4%B9%93%E7%90%83&hobby=%E8%B6%B3%E7%90%83*/

      /*引入json轉化序列後就可以調用下面的方法*/
      var serialize = $('#myform').serializeJson();
      /*console.log(serialize);*/
      /*現在的輸出格式爲:Object { username: "何龍", age: "12", hobby: (3) […] }這正是Ajax請求時候的傳參方式*/

      //將參數發送給服務器
      //只有使用下面這種方式纔不會出錯(先記住)
      $.ajax({
        type:"post",
        url:"${pageContext.request.contextPath}/formJson",
        data:JSON.stringify(serialize),
        dataType:'json',
        contentType:'application/json',
        success:function (data) {
          console.log("成功")
          console.log(data);
        },
        error:function(){
          console.log("失敗")
        }
      });

    });

  });

  </script>
  </body>
</html>

後端的前端控制器:

package com.helong.web.controller;

import com.helong.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/formJson")
    @ResponseBody/*將數據返回爲json格式*/
    public User getJson(@RequestBody  User user){
        System.out.println(user);
         //將數據返回給前端
        return user;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章