美文网首页IT@程序员猿媛Java架构技术进阶SpringBoot精选
前台数据提交后台,数组、数组对象,接收 OR 提交 卡在了哪里?

前台数据提交后台,数组、数组对象,接收 OR 提交 卡在了哪里?

作者: 程就人生 | 来源:发表于2019-09-28 21:54 被阅读0次

前台提交到后台的数据类型,最常用的主要有这几种:对象、单个数据类型、数组、数组对象。其中对象最为常用,对象也可分为两种提交方式,一种是表单提交,一种是使用ajax提交,对于前后端分离的项目来说,最常用的则是ajax提交。

对象里面包括多个属性,每个属性可以是不同的基本数据类型,比如String字符串类型,Byte类型,Integer类型,datetime数据类型等等。

如果没有对应的对象,能否把一个表单中的数据封装一个map集合,提交到后台呢,实践证明也是可以的,只不过需要将这个map集合先封装到对象里。这种情况也是有使用场景的,比如把查询表单中的所有查询条件,封装成一个map集合,传递到后台,进行查询操作。这样写可以省下不少代码,后期维护起来也方便。

单个数据类型,就是单一的一个属性,比如一个String字符串类型,一个Byte类型,一个Integer类型等等。
数组,可以是String字符串数组,也可以是Integer数组,同一数据类型的数组。

数组对象,则是一种对象的集合,这种比较少用,但是会有用到的地方,比如批量提交表单,则会用到数组对象。

简单用springboot搭了一个简易的svn项目,对于上面的这几种类型做个demo。
后台代码如下:

importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestBody;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.servlet.ModelAndView;
 
importcom.example.demo.entity.Pager;
importcom.example.demo.entity.Test;
 
/**
 * 数据类型接收测试
 * @author 程就人生
 * @date 2019年9月3日
 */
@RequestMapping("/test")
@RestController
public class TestController {
 
    /**
     * 初始化页面
     * @return
     *
     */
    @GetMapping("/index")
    public ModelAndView index(){     
        return new ModelAndView("/index");
    }
   
    /**
     * 以路径path的形式放在请求的路径后面
     * @param userUid
     * @return
     *
     */
    @GetMapping("/{userUid}")
    public Object get(@PathVariable String userUid){
        System.out.println("1:" + userUid);
        return userUid;
    }
   
    /**
     * 直接接收,前台可以是传统的放在问号后面,也可以放在data里
     * @param userUid
     * @return
     *
     */
    @GetMapping
    public Object get2(String userUid){
        System.out.println("1a:" + userUid);
        return userUid;
    }
   
    /**
     * 对字符串数组的接收,第一种写法,用可变参数接收
     * @param userUids 用可变参数接收,接收到的形式为包含一个字符串或多个字符串的数组
     * @return
     *
     */
    @GetMapping("/array")
    public Object getArray(String... userUids){
        for(String userUid : userUids){
            System.out.println("2:" + userUid);
        }
        return userUids;
    }
   
    /**
     * 对数组的接收,第二种写法,比较传统的写法
     * @param userUids
     * @return
     *
     */
    @GetMapping("/array2")
    public Object getArray2(String[] userUids){
        for(String userUid : userUids){
            System.out.println("2a:" + userUid);
        }
        return userUids;
    }
       
    /**
     * 对象的接收,可以用form表单提交,或者放在ajax请求的data里面,放在data里面时,需要进行序列化处理
     * @param test
     * @return
     *
     */
    @PostMapping
    public Object add(Test test){
        System.out.println("3:" + test.getUserName());
        System.out.println("3:" + test.getUserPwd());
        return test;
    }
   
    /**
     * 对数组对象的接收,前台必须是以json的形式发送请求
     * @RequestBody代表前台必须使用ajax请求,并且contentType类型必须为:"application/json"
     * 前台传递过来的数据还必须使用JSON.stringify()转换为一个 JSON字符串
     * @param testList
     * @return
     *
     */
    @PostMapping("/array")
    public Object addArray(@RequestBodyTest... testList){
        for(Test test : testList){
            System.out.println("4:" + test.getUserName());
            System.out.println("4:" + test.getUserPwd());
        }
        return testList;
    }  
   
    /**
     * 提交map集合,把map集合放在一个对象里面,作为对象的一个属性进行传递
     * @param map
     * @return
     *
     */
    @GetMapping("/list")
    public Object searchByCriteria(Pager pager){ 
        System.out.println("5:" + pager.getCondition().get("userName2"));
        System.out.println("5:" + pager.getCondition().get("userPwd2"));
        return pager;
    }
}

前台页面代码如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport"content="width=device-width, initial-scale=1.0">
 
    <title>新增</title>
 
    <meta name="keywords"content="">
    <meta name="description"content="">
 
    <!--[if lt IE 9]>
    <meta http-equiv="refresh" content="0;ie.html" />
    <![endif]-->
    <link rel="stylesheet"media="screen" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.min.css">
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>   
</head>
<body>   
    <form id="form1">
        <input type="text"name="userUid" />
        <button id="singleButton"type="button" >提交一个字符串1</button>
        <button id="singleButton2"type="button" >提交一个字符串2</button>
        <button id="singleButton3"type="button" >提交一个字符串3</button>    
    </form>   
    <form id="form2">
        <input type="text" name="userUid1"/>
        <input type="text" name="userUid1"/>
        <input type="text" name="userUid1"/>
        <input type="text" name="userUid1"/>
        <button id="arrayButton"type="button" >提交一个字符串数组</button>
    </form>   
    <form id="form3">
        <input type="text"name="userName" />
        <input type="text"name="userPwd" />
        <button id="formButton"type="button" >提交表单</button>
    </form>   
    <form id="form4">
        <input type="text" name="userName1"/>
        <input type="text"name="userPwd1" />
        <input type="text"name="userName1" />
        <input type="text"name="userPwd1" />
        <input type="text"name="userName1" />
        <input type="text"name="userPwd1" />
        <button id="formArrayButton"type="button" >提交一组表单</button>
    </form>   
    <form id="form5">
        <input type="text" name="userName2"/>
        <input type="text"name="userPwd2" />
        <button id="mapButton"type="button" >提交多个属性</button>
    </form>
</body>
<script th:inline="javascript">
    //提交一个字符串,第一种方式
    $("#singleButton").click(function(){
    $.ajax({
        url:'/test/'+$("input[name='userUid']").val(),
        type:'get',
        data:{},
        dataType:'json',
        success:function(data){
         
        }
        });
    });
    //提交一个字符串,第二种方式
    $("#singleButton2").click(function(){
    $.ajax({
        url:'/test',
        type:'get',
        data:{'userUid':$("input[name='userUid']").val()},
        dataType:'json',
        success:function(data){
         
        }
        });
    });
    //提交一个字符串,第三种方式
    $("#singleButton3").click(function(){
    $.ajax({
        url:'/test?userUid='+$("input[name='userUid']").val(),
        type:'get',
        data:{},
        dataType:'json',
        success:function(data){
         
        }
        });
    });
   
    //提交一个数组
    $("#arrayButton").click(function(){
    var array = new Array();
    $("input[name='userUid1']").each(function(i){
        if($(this).val()!=''){
            array[i] = $(this).val();
        }
    });
    $.ajax({
        url:'/test/array',
        type:'get',
        data:{'userUids':array.join(",")},//数组必须转化成逗号分隔的字符串
        dataType:'json',
        success:function(data){
         
        }           
     });
    });
    //提交一个表单
    $("#formButton").click(function(){
    $.ajax({
        url:'/test',
        type:'POST',
        data:$("#form3").serialize(),//对整个表单进行提交,需要对form表单进行序列化
        dataType:'json',
        success:function(data){
         
        }
     });
    });
    //获取表单,对表单参数的封装
    $.fn.serializeList = function(){
     var arrList = new Array();
     var o = {};
     $("input[name='userName1']").each(function(i){
          o = {};
          o.userName = $("input[name='userName1']").eq(i).val();
          o.userPwd = $("input[name='userPwd1']").eq(i).val();         
          arrList[i] = o;
         });
     return arrList;
    };
   
    //提交多个表单,JSON.stringify() 参考资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
    $("#formArrayButton").click(function(){
    $.ajax({
        url:'/test/array',
        type:'post',
        data: JSON.stringify($("#form4").serializeList()),//转换为一个 JSON字符串,特别重要
        dataType:'json',
        contentType: "application/json",//以json的形式提交,同样重要
        success:function(data){
         
        }             
     });
    });   
   
    //获取查询参数,对查询参数的封装
    $.fn.serializeObject = function(){
     var o = {};
     var a = this.serializeArray();
     $.each(a, function() {
         if (o[this.name] !== undefined) {
             if (!o[this.name].push) {
                 o[this.name] = [o[this.name]];
             }
             o[this.name].push(this.value || '');
         } else {
             o[this.name] = this.value || '';
         }
     });
     return o;
    };
    //把不确定的字段封装成对象里的一个map集合,map集合作为对象的一个属性进行获取
    $("#mapButton").click(function(){
    $.ajax({
        url:'/test/list',
        type:'get',
        data:{'condition':$("#form5").serializeObject()},
        dataType:'json',
        success:function(data){
         
        }            
     });
    });
   
</script>
</html>

启动项目,界面如下:



界面有点丑,没有美化,没有css文件,js文件只引用了jquery,运行结果还是很漂亮的:



总结
这个demo中的后台方法命名,基本上遵循了RESTFul设计风格,即使练习也要遵守规范,养成一个好的习惯吧。有时由于前后台分离,昨天用过的方法,可能几天不写就忘记了,像上面的数组,数组对象的处理,每次用时都要搜一搜怎么写的,这次又用到了,既然如此,就整理一个全面的demo,以备后用。

相关文章

  • 前台数据提交后台,数组、数组对象,接收 OR 提交 卡在了哪里?

    前台提交到后台的数据类型,最常用的主要有这几种:对象、单个数据类型、数组、数组对象。其中对象最为常用,对象也可分为...

  • php--编程

    作者:烨竹 一、前后台数据传递 前台数据提交:get,post后台数据接收:$GRT,$POST,$REQUEST...

  • 前台传数组或list,后台接收

    前台传数组或list,后台接收 ==springboot== ==springmvc== 在前台转json字符串...

  • springmvc使用

    springmvc高级参数绑定 数组绑定表单中如果有多个相同的name需要提交数据, 服务器可以使用数组的方式接收...

  • SpringMVC-接收表单数据的方式

    前台提交表单数据到后台进行处理 form 表单提交数据,get方法会将数据通过请求url方式向后台传送,post方...

  • JavaScript 通信 / Ajax

    Ajax 表单提交 在HTML中提供了表单提交的功能,我们可以通过表单把数据从前台提交到后台 在HTML的DOM中...

  • JQuery param %5B%5D 数据参数序列化问题

    问题:前台传数组对象,后台接收时,参数后面会多出一对中括号例如:{'param_integer':[1,2,3]}...

  • 反射模拟同对象的属性拷贝

    应用场景 程序有一个数据库对象进行update操作如:前台form表单提交对象Entity(from)到后台做数据...

  • 前端—表单表格

    一、表单 作用:将前台用户数据通过get或post请求方式,提交给后台,并将新页面标签中接收与后台相应 请求方式:...

  • web开发之数据的接收

    前台将数据汇总之后通过ajax发送到后台,如果前台将数据汇总为json对象,那么后台怎么接收?如果前台将数据汇总为...

网友评论

    本文标题:前台数据提交后台,数组、数组对象,接收 OR 提交 卡在了哪里?

    本文链接:https://www.haomeiwen.com/subject/abfkyctx.html