前后端交互表单提交方式总结(springmvc+vue+form)

表单提交的方式总结(后端使用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

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值