Spring Boot 学习笔记(六) 整合 RESTful 参数传递

2,848 阅读8分钟

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作为参数传递的测试页面。添加以下代码:

1<head>
2    ....
3    <script src="/learning/js/jquery.min.js"></script>
4</head>

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

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

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

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

2. GET 方式传递基本类型

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

2.1 PathVariable 注解

ParameterController:

1@RestController
2@RequestMapping("/parameter")
3public class ParameterController {
4    private Logger logger = LoggerFactory.getLogger(ParameterController.class);
5
6    @GetMapping("/getString/{str}")
7    public String getString(@PathVariable(value = "str") String str){
8        logger.info("GET 传参,传递基本类型。str:{}",str);
9        return "收到参数:" + str;
10    }
11}
12

ParameterPassing.html

1<body>
2    <h2>测试参数传递</h2>
3    <button id = "bt1">get传递String</button>
4    <input id="in1" type="text">
5</body>
6<script>
7    $("#bt1").click(
8        function () {
9            $.ajax(
10                {
11                    url:"/learning/parameter/getString/"+$("#in1").val(),
12                    method:"GET",
13                    success:function (result) {
14                        alert(result);
15                    }
16                }
17            )
18        }
19    );
20</script>

2.2 RequestParam 注解

ParameterController

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

ParameterPassing.html

1    $("#bt2").click(
2        function () {
3            $.ajax(
4                {
5                    url: "/learning/parameter/getName",
6                    method: "GET",
7                    data: {
8                        name: $("#in2").val()
9                    },
10                    success: function (result) {
11                        alert(result);
12                    }
13                }
14            );
15        }
16    );
17    //拼接url方式
18    $("#bt3").click(
19        function () {
20            $.ajax(
21                {
22                    url: "/learning/parameter/getName?name="+$("#in3").val(),
23                    method: "GET",
24                    success: function (result) {
25                        alert(result);
26                    }
27                }
28            );
29        }
30    );

注意:

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

1    @PostMapping("/postString/{str}")
2    public String postString(@PathVariable(value = "str") String str){
3        logger.info("POST 传参,传递基本类型。str:{}",str);
4        return "收到参数:" + str;
5    }

ParameterPassing.html

1    $("#bt4").click(
2        function () {
3            $.ajax(
4                {
5                    url:"/learning/parameter/postString/"+$("#in4").val(),
6                    method:"POST",
7                    success:function (result) {
8                        alert(result);
9                    }
10                }
11            )
12        }
13    );

3.2 RequestParam 注解

ParameterController

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

ParameterPassing.html

1    $("#bt5").click(
2        function () {
3            $.ajax(
4                {
5                    url: "/learning/parameter/postName",
6                    method: "POST",
7                    data: {
8                        name: $("#in5").val()
9                    },
10                    success: function (result) {
11                        alert(result);
12                    }
13                }
14            );
15        }
16    );
17    //拼接url方式
18    $("#bt6").click(
19        function () {
20            $.ajax(
21                {
22                    url: "/learning/parameter/postName?name="+$("#in6").val(),
23                    method: "POST",
24                    success: function (result) {
25                        alert(result);
26                    }
27                }
28            );
29        }
30    );

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

4. POST 传递引用类型

PathVariable 注解不支持引用类型。

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

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

ParameterController

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

ParameterPassing.html

1    $("#bt7").click(
2        function () {
3            var accountInfo = {
4                accountId: 123,
5                name: $("#in7").val(),
6                pwd: "root",
7                balance: 123
8            };
9            $.ajax(
10                {
11                    url: "/learning/parameter/postAccount",
12                    method: "POST",
13                    data: JSON.stringify(accountInfo),
14                    contentType:"application/json",
15                    success: function (result) {
16                        alert(JSON.stringify(result));
17                    }
18                }
19            );
20        }
21    );

5. 传递数组

5.1 传递基本类型的数组

ParameterController

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

ParameterPassing.html

1    $("#bt8").click(
2        function () {
3            var names = ["a","b","c",$("#in8").val()];
4            $.ajax(
5                {
6                    url: "/learning/parameter/postNames",
7                    method: "POST",
8                    data: JSON.stringify(names),
9                    contentType:"application/json",
10                    success: function (result) {
11                        alert(JSON.stringify(result));
12                    }
13                }
14            );
15        }
16    );

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

ParameterController

1    @PostMapping("/postAccountList")
2    public List<AccountInfo> postAccountList(@RequestBody List<AccountInfo> accounts) {
3        logger.info("GET 传参,传递基本类型。str:{}", accounts.4    [native code]
5}">toString());
6        return accounts;
7    }

ParameterPassing.html

1    $("#bt9").click(
2        function () {
3            var accounts = [];
4
5            var accountInfo1 = {
6                accountId: 123,
7                name: $("#in9").val(),
8                pwd: "root",
9                balance: 123
10            };
11            accounts.push(accountInfo1);
12            var accountInfo2 = {
13                accountId: 123,
14                name: $("#in9").val(),
15                pwd: "root",
16                balance: 123
17            };
18            accounts.push(accountInfo2);
19            $.ajax(
20                {
21                    url: "/learning/parameter/postAccountList",
22                    method: "POST",
23                    data: JSON.stringify(accounts),
24                    contentType:"application/json",
25                    success: function (result) {
26                        alert(JSON.stringify(result));
27                    }
28                }
29            );
30        }
31    );

转载请注明出处
本文链接:zdran.com/20180725.ht…