1. 程式人生 > 其它 >前後端互動表單提交方式總結(springmvc+vue+form)

前後端互動表單提交方式總結(springmvc+vue+form)

技術標籤:springboot前端vuejsajaxhtml

表單提交的方式總結(後端使用springmvc)

準備工作

1.實體類

package com.ckf.springbootswagger.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.
ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; /** * @author 安詳的苦丁茶 * @version 1.0 * @date 2020/3/13 14:51 */ @ApiModel(value = "使用者實體類") public
class UserInfo { @TableId(type = IdType.AUTO) @ApiModelProperty(value = "使用者ID",required = true,example = "1",dataType = "Integer") private Integer id; @ApiModelProperty(value = "使用者名稱稱",required = true,example = "root") private
String username; @ApiModelProperty(value = "使用者密碼", required = true,example = "root") private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserInfo{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }

2.匯入js庫

jquery.serializejson.min.js

jquery-1.8.3.min.js

jquery.serializejson.min.js

axios.min.js
vue.js

3.表單提交成功的頁面

success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>表單提交後的成功頁面</title>
</head>
<body>
<h1>
跳轉到form表單提交後的成功頁面
</h1>
</body>
</html>

4.表單提交失敗的頁面

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>表單提交後的失敗頁面</title>
</head>
<body>
<h1 style="color: red">
跳轉到form表單提交後的失敗頁面
</h1>
</body>
</html>

1.url表單提交和ajax表單提交

說明:

這裡我使用的事jQuery封裝好的ajax

FormController

package com.ckf.springbootswagger.controller;


import com.ckf.springbootswagger.entity.UserInfo;
import com.ckf.springbootswagger.pojo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * @Auther: shaoming
 * @Date: 2020/12/3 00:57
 * @Description:
 測試表單提交的方式
 */
@Controller
@Api(tags = "表單提交的幾種方式")
public class FormController {
    /**
     * 跳轉到form表單測試頁面
     */
     @GetMapping("/toformhtml")//get請求
         @ApiOperation(value = "跳轉到form表單測試頁面", notes = "跳轉到form表單測試頁面",
                 httpMethod = "GET")
         public  String toFormHtml() {
             return "form";
         }
    /**
     * 跳轉到form表單提交後的成功頁面
     */
     @GetMapping("/tosuccess")//get請求
         @ApiOperation(value = "跳轉到form表單提交後的成功頁面", notes = "跳轉到form表單提交後的成功頁面",
                 httpMethod = "GET")
         public  String toSuccessHtml() {
             return "success";
         }
    /**
     * 跳轉到form表單提交後的失敗頁面
     */
     @GetMapping("/toerror")//get請求
         @ApiOperation(value = "跳轉到form表單提交後的失敗頁面", notes = "跳轉到form表單提交後的失敗頁面",
                 httpMethod = "GET")
         public  String torrorHtml() {
             return "error";
         }

    /**
     * 1.使用get請求,屬性和和物件的get/set的屬性名相對應
     */
     @GetMapping("/getfiledbygetset")//get請求
         @ResponseBody
         @ApiOperation(value = "1.使用get請求,屬性和和物件的get/set的屬性名相對應",
                 notes = "1.使用get請求,屬性和和物件的get/set的屬性名相對應", httpMethod = "GET")
         public R getfiledBygetset(UserInfo user) {
         System.out.println(user);
         return R.ok().put("data",user);
         }
    /**
     * 2.使用post請求,屬性和和物件的get/set的屬性名相對應
     */
     @PostMapping("/postfiledbygetset")
         @ResponseBody
         @ApiOperation(value = "2.使用post請求,屬性和和物件的get/set的屬性名相對應",
                 notes = "2.使用post請求,屬性和和物件的get/set的屬性名相對應", httpMethod = "POST")
         public R postfiledBygetset(UserInfo user) {
         System.out.println(user);
         return R.ok().put("data",user);
         }

    /**
     * 3.使用get請求,屬性和和物件的get/set的屬性名相對應,重定向到成功或者頁面
     */
     @GetMapping("/getfiledbygetsettosuccess")//get請求
//         @ResponseBody
         @ApiOperation(value = "3.使用get請求,屬性和和物件的get/set的屬性名相對應,重定向到成功或者失敗頁面",
                 notes = "3.使用get請求,屬性和和物件的get/set的屬性名相對應,重定向到成功或者失敗頁面", httpMethod = "GET")
         public String getfiledBygetsetToSuccessHtml(UserInfo user) {
         System.out.println(user);
         if(user.getUsername().equalsIgnoreCase("root")&&user.getPassword().equalsIgnoreCase("root")){

         return "redirect:/tosuccess";
         }else {
         return "redirect:/toerror";
         }
         }
    /**
     * 4.使用post請求,請求引數以json的形式傳入
      */

     @PostMapping("/postjson")
         @ResponseBody
         @ApiOperation(value = "4.使用post請求,請求引數以json的形式傳入",
                 notes = "4.使用post請求,請求引數以json的形式傳入", httpMethod = "POST")
         public R postjson(@RequestBody UserInfo user) {
         System.out.println(user);
         return R.ok().put("data",user);
         }


    /**
     * 測試vue的表單提交
      */
     @GetMapping("/")//get請求
        // @ResponseBody
         @ApiOperation(value = "toVueForm", notes = "", httpMethod = "")
         public String toVueForm(HttpServletRequest request) {
             return null;
         }
}

form.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試各類的表單提交</title>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/jquery.serializejson.min.js"></script>
</head>
<body>
<h1 style="text-align: center">表單測試頁面</h1>
<hr>
<div style="text-align: center">
    <h3>get方式提交表單</h3>
    <form th:action="@{/getfiledbygetset}" method="get">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="submit" th:value="提交">
    </form>
</div>
<hr><hr>
<div style="text-align: center">
    <h3>post方式提交表單</h3>
    <form th:action="@{/postfiledbygetset}" method="post">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="submit" th:value="提交">
    </form>
</div>
<hr><hr>
<div style="text-align: center">
    <h3>get方式提交表單,跳轉到form表單提交後的成功或者失敗頁面
        正確username <br> root  , password <br> root
    </h3>
    <form th:action="@{/getfiledbygetsettosuccess}" method="get">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="submit" th:value="提交">
    </form>
</div>
<hr><hr>

<div style="text-align: center">
    <h3>ajax的get方式提交表單</h3>
    <form action="#" method="get" id="form1">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
    </form>
</div>
<hr><hr>
<div style="text-align: center">
    <h3>ajax的get方式提交表單,並跳轉到成功頁面</h3>
    <form action="#" method="get" id="form2">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="button" th:value="提交按鈕" id="btn5">
    </form>
</div>
<hr><hr>
<div style="text-align: center">
    <h3>ajax的post方式,表單資料以json格式提交</h3>
    <form action="#" method="get" id="form3">
        <input type="text" name="id">
        <br>
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="button" th:value="提交按鈕" id="btn6">
    </form>
</div>
<hr><hr>
<input type="button" th:value="ajax的get方式" id="btn1">
<hr><hr>
<input type="button" th:value="ajax的post方式" id="btn2">
<hr><hr>
<input type="button" th:value="ajax的get方式提交表單" id="btn3">
<hr><hr>
<button id="btn4">ajax的post方式,引數為json格式</button>
<hr><hr>
<button id="btn7">在localStorge中儲存使用者的資訊username:root, password:root</button>
<script>
    $("#btn7").click(function () {
        var userInfo = {username:"root",password:"root"};
        var userInfoJson = JSON.stringify(userInfo);
        //把user的資訊放到localStorage中
        localStorage.setItem("userInfo",userInfoJson);
    });
    $("#btn6").click(function(){
        var json = JSON.stringify($("#form3").serializeJSON());
        // var a = $("#form3").serialize();
        $.ajax({
            url: "/postjson",
            type: "POST",
            data:json,
            async: true,
            dataType:"JSON",
            contentType:"application/json",
            success:function(data){
                //把localStorage中的json資料轉為json物件
                var userInfo = JSON.parse(localStorage.getItem("userInfo"));
                console.log(userInfo);
                console.log(data);
                console.log(data.data);
                if(userInfo.username.toLowerCase()==data.data.username&&userInfo.password.toLowerCase()==data.data.password){
                    window.location.href="tosuccess";
                }else{
                    window.location.href="toerror";
                }
            },
            error:function(err){
                console.log(err.statusText);
                console.log('異常');
            }
        })
    });


    $("#btn5").click(function(){
        var params = $("#form2").serialize();
        $.ajax({
            url: "/postfiledbygetset",
            type : "POST",//請求的方式
            data : params,//請求的引數
            async : true,//預設為true,表示非同步請求
            dataType : "JSON",//返回的資料時json格式的物件,如果是字元竄,簡單型別一般就是text型別
            success : function(data){
                console.log(data);
                if(data.data.username.toLowerCase()=='root'&&data.data.password.toLowerCase()){
                    if(confirm("是否跳轉到成功頁面")){
                    window.location.href="/tosuccess";
                    }else{
                        window.location.reload();
                    }
                }else{
                    window.location.href="/toerror";
                }
            },//定義成功的回撥函式
            error : function() {
                alert("ajax請求失敗");
            }//失敗的回撥函式
        })
    });
    $("#btn3").click(function(){
        var params = $("#form1").serialize();
        $.ajax({
            url: "/postfiledbygetset",
            type : "POST",//請求的方式
            data : params,//請求的引數
            async : true,//預設為true,表示非同步請求
            dataType : "JSON",//返回的資料時json格式的物件,如果是字元竄,簡單型別一般就是text型別
            success : function(data){
                console.log(data);
            },//定義成功的回撥函式
            error : function() {
                alert("ajax請求失敗");
            }//失敗的回撥函式
        })
    });


    $("#btn1").click(function(){
        $.ajax({
            url : "/getfiledbygetset?id=1&password=root&username=root",//請求的url
            type : "GET",//請求的方式
            data : null,//請求的引數
            async : true,//預設為true,表示非同步請求
            dataType : "JSON",//返回的資料時json格式的物件,如果是字元竄,簡單型別一般就是text型別
            success : function(data){
                console.log(data);
            },//定義成功的回撥函式
            error : function() {
                alert("ajax請求失敗");
            }//失敗的回撥函式
        })
    });

    $("#btn2").click(function(){
        $.ajax({
            url: "/postfiledbygetset",
            type: "POST",
            data:{id:1,username:'root',password:'root'},
            // data:{},
            async: true,
            dataType:"JSON",
            success:function(data){
                console.log(data);
            },
            error:function(err){
                console.log(err.statusText);
                console.log('異常');
            }
        })
    });

    $("#btn4").click(function(){
        var jsporject={id:1,username:'root',password:'root'};
        var proToJson = JSON.stringify(jsporject);
        $.ajax({
            url: "/postjson",
            type: "POST",
            data:proToJson,
            // data:{},
            async: true,
            dataType:"JSON",
            contentType:"application/json",
            success:function(data){
                console.log(data);
            },
            error:function(err){
                console.log(err.statusText);
                console.log('異常');
            }
        })
    });

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

2.vue+axios的表單提交

VueFormController

package com.ckf.springbootswagger.controller;

import com.ckf.springbootswagger.entity.UserInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: shaoming
 * @Date: 2020/12/7 15:40
 * @Description: 測試Vue的表單提交
 * get 表單提交
 * post 表單提交
 */
@RestController
public class VueFormController {
    /**
     * vue的get表單的提交
     */
    @GetMapping("/vueformget")
    @ApiOperation(value = "vue-form-get", notes = "vue表單的get提交", httpMethod = "get")
    public UserInfo vueFormGet(UserInfo userInfo) {
        return userInfo;
    }
    /**
     * vue的post表單提交
     */
    @PostMapping("/vueformpost")
    @ApiOperation(value = "vue-form-post", notes = "vue表單的post提交", httpMethod = "post")
    public UserInfo vueFormPost(UserInfo userInfo) {
        return userInfo;
    }
    /**
     * vue的post提交傳json
     */
    @PostMapping("/vuepostjson")//get請求
    @ApiOperation(value = "vue-post-json", notes = "vue的post提交傳json資料", httpMethod = "post")
    public UserInfo vueFormPostJson(@RequestBody  UserInfo userInfo) {
        System.out.println("進入方法(vue表單的post提交傳json資料)");
        return userInfo;
    }
    /**
     * vue的post繫結mode的表單提交
     */
    @PostMapping("/vueformmodepost")
    @ApiOperation(value = "vue-form-mode-post", notes = "vue表單封裝到formdata物件的post提交", httpMethod = "post")
    public UserInfo vueformModePost(UserInfo userInfo) {
        return userInfo;
    }
    /**
     * vue的post繫結mode傳json的表單提交
     */
    @PostMapping("/vueformmodejsonpost")
    @ApiOperation(value = "vue-form-mode-json-post", notes = "vvue的post繫結mode傳json的表單提交", httpMethod = "post")
    public UserInfo vueformModeJsonPost(@RequestBody UserInfo userInfo) {
        return userInfo;
    }
}

vue_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入vue.js庫 -->
    <script src="js/vue.js"></script>
    <!-- 引入引入axios庫庫 -->
    <script src="js/axios.min.js"></script>
</head>
<body>
<!-- vue的div作為容器 -->
<div id="app">
    <p>{{msg}}</p>
    <button @click="f1">測試單擊事件</button>
    <hr>
    <button @click="f2">測試post獲取json資料</button>
    <hr>
    <button @click="f4">Form物件轉為json物件和json格式的字元竄</button>
    <hr>
    <button @click="f5">json格式字元竄轉為FormData物件</button>
    <hr>
    <!-- vue的get表單的提交(就是普通的get提交) -->
    <form action="/vueformget" method="GET">
        <input type="text" name="id" value="1"/>
        <br>
        <input type="text" name="username" value="root"/>
        <br>
        <input type="text" name="password" value="root"/>
        <br>
        <input type="submit" value="提交按鈕">
    </form>
    <hr>
    <!-- vue的post表單提交 -->
    <form action="/vueformpost" method="POST">
        <input type="text" name="id" value="1"/>
        <br>
        <input type="text" name="username" value="root"/>
        <br>
        <input type="text" name="password" value="root"/>
        <br>
        <input type="submit" value="提交按鈕">
    </form>
    <hr>
    <!-- vue的post繫結mode的表單提交 -->
    <form action="/" method="POST">
        <input type="text" v-model="userInfo.id" name="id" value="1"/>
        <br>
        <input type="text" v-model="userInfo.username" name="username" value="root"/>
        <br>
        <input type="text" v-model="userInfo.password" name="password" value="root"/>
        <br>
        <input type="button" @click="f3" value="提交按鈕">
    </form>
    <hr>
    <!-- vue的post繫結mode傳json的表單提交 -->
    <form action="/" method="POST">
        <input type="text" v-model="userInfo.id" name="id" value="1"/>
        <br>
        <input type="text" v-model="userInfo.username" name="username" value="root"/>
        <br>
        <input type="text" v-model="userInfo.password" name="password" value="root"/>
        <br>
        <input type="button" @click="f6" value="提交按鈕">
    </form>
</div>
<script>
    const app = new Vue({
        el:"#app",
        data:{
           msg:"helloword",
           userInfo:{},
        },
    methods:{
            f1(){
                alert("測試事件成功~helloword")
            },
            f2(){
                var jsonData={
                    id: 1,
                    username: "root",
                    password: "root"
                }
                axios({
                    method:"post",
                    url:"http://localhost:8081/vuepostjson",
                    data:jsonData
                }).then(res=>{
                    console.log(res.data);
            });
            },
        f3(){
            var formData = new FormData();
            formData.append("id",this.userInfo.id);
            formData.append("username",this.userInfo.username);
            formData.append("password",this.userInfo.password);
           // var _this = this;
            console.log(formData);
            axios({
                method:"post",
                url:"http://localhost:8081/vueformmodepost",
                data:formData
            }).then(res=>{
                console.log(res.data);
        });
        },
        f4(){
            var formData = new FormData();
            formData.append("id",1);
            formData.append("username","root");
            formData.append("password","root");
            var jsonData = {};
            //FormData物件轉為json物件
            formData.forEach((value, key) => jsonData[key] = value);
            console.log("FormData物件轉為json物件");
            console.log(jsonData);
            alert(typeof (jsonData));
            //json物件轉為json格式的字元竄
            var jsonDataString = JSON.stringify(jsonData);
            console.log("json物件轉為json格式的字元竄");
            console.log(jsonDataString);
            alert(typeof (jsonDataString));
        },
        f5(){
            var jsonObj={
                id: 1,
                username: "root",
                password: "root"
            };
            var jsonString = JSON.stringify(jsonObj);
            console.log("json物件轉為json格式的字元竄");
            console.log(jsonString);
            alert(typeof (jsonString))
            console.log("json格式的字元竄轉為json物件");
            var parseJsonObj = JSON.parse(jsonString);
            console.log(parseJsonObj);
            alert(typeof (parseJsonObj))

            const formData = new FormData();
            Object.keys(jsonObj).forEach((key) => {
                formData.append(key, jsonObj[key]);
        });
            var jsonData = {};
            //FormData物件轉為json物件
            formData.forEach((value, key) => jsonData[key] = value);
            console.log("FormData物件轉為json物件");
            console.log(jsonData);
        },
        f6(){
                alert(1111);
                //把雙向繫結的資料放到formData物件裡面
                var formData = new FormData();
                formData.append("id",this.userInfo.id);
                formData.append("username",this.userInfo.username);
                formData.append("password",this.userInfo.password);
                //formData物件轉為json格式的字元竄
            //1.forData物件資料轉為json物件
            var jsonData = {};
            //FormData物件轉為json物件
            formData.forEach((value, key) => jsonData[key] = value);
            //json物件轉為json格式的字元竄
            var jsonDataString = JSON.stringify(jsonData);
            console.log(jsonDataString);
            axios({
                method:"post",
                url:"http://localhost:8081/vueformmodejsonpost",
                data:jsonDataString
            }).then(res=>{
                console.log(res.data);
        });
        }

    }
    });
</script>
</body>
</html>

個人部落格網址

個人csdn部落格網址:https://blog.csdn.net/shaoming314

jam

個人部落格網址:www.shaoming.club

halo

個人gitee地址:https://gitee.com/shao_ming314/note

111

mData.forEach((value, key) => jsonData[key] = value);
//json物件轉為json格式的字元竄
var jsonDataString = JSON.stringify(jsonData);
console.log(jsonDataString);
axios({
method:“post”,
url:“http://localhost:8081/vueformmodejsonpost”,
data:jsonDataString
}).then(res=>{
console.log(res.data);
});
}

}
});
```

個人部落格網址

個人csdn部落格網址:https://blog.csdn.net/shaoming314

[外鏈圖片轉存中…(img-NMUNf3Ff-1608393889689)]

個人部落格網址:www.shaoming.club

[外鏈圖片轉存中…(img-TlW7bjBv-1608393889692)]

個人gitee地址:https://gitee.com/shao_ming314/note

[外鏈圖片轉存中…(img-hcthUmZd-1608393889693)]