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 Boot 学习笔记(六) 整合 RESTful 参数传递的更多相关文章

  1. Spring Boot学习笔记:整合Shiro

    Spring Boot如何和Shiro进行整合: 先自定义一个Realm继承AuthorizingRealm,并实现其中的两个方法,分别对应认证doGetAuthenticationInfo和授权do ...

  2. Spring Boot学习笔记(五)整合mybatis

    pom文件里添加依赖 <!-- 数据库需要的依赖 --> <dependency> <groupId>org.mybatis.spring.boot</gro ...

  3. Spring Boot学习笔记:整合H2数据库

    H2数据库:java语言编写的嵌入式sql数据库.可以和应用一起打包发布. H2有三种连接模式(Connection Modes): Embedded mode (local connections ...

  4. Spring Boot学习笔记(六)mybatis配置多数据源

    application.properties #数据库配置 #数据源类型 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # ...

  5. Spring Boot学习笔记2——基本使用之最佳实践[z]

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

  6. Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档

    1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...

  7. Spring Boot 学习笔记--整合Thymeleaf

    1.新建Spring Boot项目 添加spring-boot-starter-thymeleaf依赖 <dependency> <groupId>org.springfram ...

  8. spring boot整合jsp的那些坑(spring boot 学习笔记之三)

    Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency>            <groupId>or ...

  9. Java框架spring Boot学习笔记(六):Spring Boot事务管理

    SpringBoot和Java框架spring 学习笔记(十九):事务管理(注解管理)所讲的类似,使用@Transactional注解便可以轻松实现事务管理.

随机推荐

  1. java 练习题带答案

    第一题 int x = 1,y=1; if(x++==2 & ++y==2) { x =7; } System.out.println("x="+x+",y=&q ...

  2. 基于SSM开发在线考试系统 Java源码

    实现的关于在线考试的功能有:用户前台:用户注册登录.查看考试信息.进行考试.查看考试成绩.查看历史考试记录.回顾已考试卷.修改密码.修改个人信息等,后台管理功能(脚手架功能不在这里列出),科目专业管理 ...

  3. Struts 2的下载和安装

    一.为Web应用增加Struts 2支持 下载和安装Struts 2步骤: 登录http://struts.apache.org/download.cgi站点,下载Struts 2的最新版,下载时有以 ...

  4. 吴裕雄--天生自然 PYTHON3开发学习:数字(Number)

    print ("abs(-40) : ", abs(-40)) print ("abs(100.10) : ", abs(100.10)) #!/usr/bin ...

  5. 12 Spring Data JPA:orm思想和hibernate以及jpa的概述和jpa的基本操作

    spring data jpa day1:orm思想和hibernate以及jpa的概述和jpa的基本操作 day2:springdatajpa的运行原理以及基本操作 day3:多表操作,复杂查询 d ...

  6. ES6 find()

    Array.prototype.find() 返回数组中满足提供测试函数的第一个元素的值,否则返回undefined let b = blogs.find(function(e) => { re ...

  7. 解决在Anaconda中的cv2在pycharm中不可使用的问题

    在Anaconda中已经安装好的opencv模块在pycharm中却不能正常使用,后来发现是pycharm使用的python环境中没有opencv的包,解决方法有两种: 方法一 在pycharm的设置 ...

  8. 微信小程序生成海报保存图片到相册小测试

    test.wxml <canvas style="width:{{imageWidth}}px;height:{{imageHeight}}px;" canvas-id=&q ...

  9. SpringBoot 1.5.x 集成 Quartz 任务调度框架

    Quartz 有分 内存方式 和 数据库方式 内存方式任务信息保存在内存中, 停机会丢失, 需手动重新执行, 数据库方式: 任务信息保存在数据库中, 重点是支持集群. 内存方式 RAMJobStore ...

  10. BZOJ2733 [HNOI2012]永无乡(并查集+线段树合并)

    题目大意: 在$n$个带权点上维护两个操作: 1)在点$u,v$间连一条边: 2)询问点$u$所在联通块中权值第$k$小的点的编号,若该联通块中的点的数目小于$k$,则输出$-1$: 传送门 上周的模 ...