zoukankan      html  css  js  c++  java
  • Spring Boot 学习笔记(六) 整合 RESTful 参数传递


    0. 前言

    前后端菜单参数传递一直是初学时的痛点,不知道参数类型与注解到底怎么样去配合。

    其实整理一下就会发现。前后端参数传递大概有这么几种情况:

    常见参数数据类型:

    • 基本类型(Stirng,int等)
    • 引用数据类型(POJO等简单对象)
    • 复杂的引用数据类型(数组、集合等)

    常见传参方式:

    • URL传参
    • RequestBody 传参

    组合一下大概有6种常见的场景。

    1. 环境准备

    环境说明:

    • RESTful 风格传参
    • 前端js: jQuery.js
    • 参数格式: json格式
    • 编码格式:UTF-8

    引入 jQuery, 下载地址,将下载好的jquery.min.js放到resources/static/js下面

    然后在 templates 下面创建一个 parameterPassing.html作为参数传递的测试页面。添加以下代码:

    <head>
        ....
        <script src="/learning/js/jquery.min.js"></script>
    </head>

    别忘了在 PageController 里面添加一个获取 parameterPassing 页面的接口

    再创建一个 ParameterController 用于接收参数的controller。

    这篇文章的所有代码都只在这两个文件中,如果文章中有不太详细的地方,可以下载源码看一下。

    PS: 本来js是需要单独一个文件的,但是为了方便学习,这里就直接写在 html 里了。

    2. GET 方式传递基本类型

    最简单的一种常见,传递一个基本类型到后台。

    2.1 PathVariable 注解

    ParameterController:

    @RestController
    @RequestMapping("/parameter")
    public class ParameterController {
        private Logger logger = LoggerFactory.getLogger(ParameterController.class);
    
        @GetMapping("/getString/{str}")
        public String getString(@PathVariable(value = "str") String str){
            logger.info("GET 传参,传递基本类型。str:{}",str);
            return "收到参数:" + str;
        }
    }
    

    ParameterPassing.html

    <body>
        <h2>测试参数传递</h2>
        <button id = "bt1">get传递String</button>
        <input id="in1" type="text">
    </body>
    <script>
        $("#bt1").click(
            function () {
                $.ajax(
                    {
                        url:"/learning/parameter/getString/"+$("#in1").val(),
                        method:"GET",
                        success:function (result) {
                            alert(result);
                        }
                    }
                )
            }
        );
    </script>

    2.2 RequestParam 注解

    ParameterController

        @GetMapping("/getName")
        public String getName(@RequestParam(value = "name") String name){
            logger.info("GET 传参,传递基本类型。str:{}",name);
            return "收到参数:" + name;
        }

    ParameterPassing.html

        $("#bt2").click(
            function () {
                $.ajax(
                    {
                        url: "/learning/parameter/getName",
                        method: "GET",
                        data: {
                            name: $("#in2").val()
                        },
                        success: function (result) {
                            alert(result);
                        }
                    }
                );
            }
        );
        //拼接url方式
        $("#bt3").click(
            function () {
                $.ajax(
                    {
                        url: "/learning/parameter/getName?name="+$("#in3").val(),
                        method: "GET",
                        success: function (result) {
                            alert(result);
                        }
                    }
                );
            }
        );

    注意:

    PathVariable 注解的参数是直接拼接在url里的,不是放在data里的。

    RequestParam 注解的参数可以放在data里,也可以拼接url,格式是 ?key=value

    PS:前后端参数的key一定要一致不然会报一个”Required String parameter ‘nae’ is not present” 的错误

    3. POST 方式传递基本类型

    Post 方式传递基本类型与Get方式基本一样。

    3.1 PathVariable 注解

    ParameterController

        @PostMappi 大专栏  Spring Boot 学习笔记(六) 整合 RESTful 参数传递ng("/postString/{str}")
        public String postString(@PathVariable(value = "str") String str){
            logger.info("POST 传参,传递基本类型。str:{}",str);
            return "收到参数:" + str;
        }

    ParameterPassing.html

        $("#bt4").click(
            function () {
                $.ajax(
                    {
                        url:"/learning/parameter/postString/"+$("#in4").val(),
                        method:"POST",
                        success:function (result) {
                            alert(result);
                        }
                    }
                )
            }
        );

    3.2 RequestParam 注解

    ParameterController

        @PostMapping("/postName")
        public String postName(@RequestParam(value = "name") String name){
            logger.info("POST 传参,传递基本类型。str:{}",name);
            return "收到参数:" + name;
        }

    ParameterPassing.html

        $("#bt5").click(
            function () {
                $.ajax(
                    {
                        url: "/learning/parameter/postName",
                        method: "POST",
                        data: {
                            name: $("#in5").val()
                        },
                        success: function (result) {
                            alert(result);
                        }
                    }
                );
            }
        );
        //拼接url方式
        $("#bt6").click(
            function () {
                $.ajax(
                    {
                        url: "/learning/parameter/postName?name="+$("#in6").val(),
                        method: "POST",
                        success: function (result) {
                            alert(result);
                        }
                    }
                );
            }
        );

    基本类型的传参方式这几种方式差不多就够用了。如果你使用的是RESTful的风格,建议使用 2.1 的格式。

    4. POST 传递引用类型

    PathVariable 注解不支持引用类型。

    RequestParam 注解也不支持引用类型,有一种做法是将json串以String类型传递。用RequestParam 注解可以,不过需要对参数进行编码。

    所以这里仅介绍下 RequestBody 注解。

    ParameterController

        @PostMapping("/postAccount")
        public AccountInfo postAccount(@RequestBody AccountInfo accountInfo) {
            logger.info("GET 传参,传递基本类型。str:{}", accountInfo);
            return accountInfo;
        }

    ParameterPassing.html

        $("#bt7").click(
            function () {
                var accountInfo = {
                    accountId: 123,
                    name: $("#in7").val(),
                    pwd: "root",
                    balance: 123
                };
                $.ajax(
                    {
                        url: "/learning/parameter/postAccount",
                        method: "POST",
                        data: JSON.stringify(accountInfo),
                        contentType:"application/json",
                        success: function (result) {
                            alert(JSON.stringify(result));
                        }
                    }
                );
            }
        );

    5. 传递数组

    5.1 传递基本类型的数组

    ParameterController

        @PostMapping("/postNames")
        public List<String> postNames(@RequestBody String[] names) {
            logger.info("GET 传参,传递基本类型。str:{}", Arrays.asList(names).toString());
            return Arrays.asList(names);
        }

    ParameterPassing.html

        $("#bt8").click(
            function () {
                var names = ["a","b","c",$("#in8").val()];
                $.ajax(
                    {
                        url: "/learning/parameter/postNames",
                        method: "POST",
                        data: JSON.stringify(names),
                        contentType:"application/json",
                        success: function (result) {
                            alert(JSON.stringify(result));
                        }
                    }
                );
            }
        );

    5.2 传递复杂类型的集合(数组)

    ParameterController

        @PostMapping("/postAccountList")
        public List<AccountInfo> postAccountList(@RequestBody List<AccountInfo> accounts) {
            logger.info("GET 传参,传递基本类型。str:{}", accounts.toString());
            return accounts;
        }

    ParameterPassing.html

        $("#bt9").click(
            function () {
                var accounts = [];
    
                var accountInfo1 = {
                    accountId: 123,
                    name: $("#in9").val(),
                    pwd: "root",
                    balance: 123
                };
                accounts.push(accountInfo1);
                var accountInfo2 = {
                    accountId: 123,
                    name: $("#in9").val(),
                    pwd: "root",
                    balance: 123
                };
                accounts.push(accountInfo2);
                $.ajax(
                    {
                        url: "/learning/parameter/postAccountList",
                        method: "POST",
                        data: JSON.stringify(accounts),
                        contentType:"application/json",
                        success: function (result) {
                            alert(JSON.stringify(result));
                        }
                    }
                );
            }
        );

    版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。未经许可不得转载!
    本文链接:https://zdran.com/20180725.html

  • 相关阅读:
    spring中的异步事件
    spring中的事件 applicationevent 讲的确实不错
    freemark2pdf
    使用Ajax生成的Excel文件并下載
    1.智帮校园App功能概况
    MVC4 Controller器同名问题
    MVC 数据验证
    补丁惹的祸-ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService
    .Net MVC4 加.html后缀报404问题
    VS2012常用快捷建(必备)
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12366618.html
Copyright © 2011-2022 走看看