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. 探讨 Git 代码托管平台的若干问题 - 2019 版

    关于 Git 版本控制软件种类繁多,维基百科收录的最早的版本控制系统是 1972 年贝尔实验室开发的 Source Code Control System.1986 年 Concurrent Vers ...

  2. normal equation(正规方程)

    normal equation(正规方程) 正规方程是通过求解下面的方程来找出使得代价函数最小的参数的: \[ \frac{\partial}{\partial\theta_j}J\left(\the ...

  3. Jenkin远程部署Tomcat8.5总结

    tomcat8.5相比之前的tomcat进入manger管理界面需要多一些设置 1. 在 $tomcathome/conf/Catalina/localhost/下创建 manager.xml , 填 ...

  4. PAT Advanced 1127 ZigZagging on a Tree (30) [中序后序建树,层序遍历]

    题目 Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree c ...

  5. 用c语言实现的几个小项目

    1.参考:Linux系统编程 2.参考:制作简单计算器 3.参考:制作2048小游戏 4.参考:五子棋实现

  6. DataStructuresAndAlgorithm--字谜游戏

    参考:http://tieba.baidu.com/p/2071585293 输入是由一些字母构成的一个二维数组以及一些单词组成.目标是要找出字谜中的单词,这些单词可能是水平.垂直或沿对角线上任何方向 ...

  7. set theory

    set theory Apart from classical logic, we assume the usual informal concept of sets. The reader (onl ...

  8. istio介绍

    核心架构 解决的问题 故障排查 1.  这个请求在哪里失败了?A有调用B吗? 2.  为什么用户的请求/页面hung住了? 3.  为什么系统这么慢?那个组件最慢? 应用容错性 1.  客户端没有配置 ...

  9. Java之异常的处理(throws)

    import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java. ...

  10. CodeForces 527C. Glass Carving (SBT,线段树,set,最长连续0)

    原题地址:http://codeforces.com/problemset/problem/527/C Examples input H V V V output input H V V H V ou ...