各种传参形式

一、QueryString

前端请求:http://localhost:8080/test/user/find?id=26&name=zhangsan

后端接收:

1.参数接收:

java 复制代码
@RequestMapping("/find")
public void find(String id,String name){
 ...
}

2.对象接收:

java 复制代码
@RequestMapping("/find")
public void find(User user){
 ...
}

自定义对象:

java 复制代码
@Data
public class User{
  private String id;
  private String name;
}

二、路径传参

前端请求:http://localhost:8080/test/user/find/26/zhangsan

后端接收:

java 复制代码
@RequestMapping("/find/{id}/{name}")
public void find(@PathVariable("id")String id,@PathVariable("name")String name){
 ...
}

三、form表单传递参数

前端form表单提交字符串请求:

java 复制代码
<form action="http://localhost:8080/test/user/find">

	username:<input type="text" name="id" /><br>
	
	password:<input type="text" name="name" /> <br>
	
	<input type="submit" value=">

</form>

后端接收:

1.参数接收

java 复制代码
@RequestMapping("/find")
public void find(String id,String name){
 ...
}

2.对象接收:

java 复制代码
@RequestMapping("/find")
public void find(User user){
 ...
}

2、form表单提交文件请求:

java 复制代码
<form action="http://localhost:8080/test/user/find" method= "post" enctype = "multipart/form-data">

    头像:<input type="file" name="photo" /><br>
    
    <input type="submit" value=">

</form>

接口:

java 复制代码
@RequestMapping("/find",method = RequestMethod.POST)
public void find(MultipartFile photo){
 ...
}

四、ajax传递json字符串

ajax传递json字符串:

java 复制代码
$.ajax({
        // 请求方式
        type:"post",
        // contentType 
        contentType:"application/json",
        // dataType
        dataType:"json",
        // url
        url:"http://localhost:8080/test/user/find",
        // 把JS的对象或数组序列化一个json 字符串
        data:{'id':1,'name':张三,'age':26,...},
        // result 为请求的返回结果对象
        success:function (result) {
            if (200 == result.code){
                alert("成功");
            }else{
                alert("失败");
            }
        }
    });

接口:

java 复制代码
@RequestMapping("/find",method = RequestMethod.POST)
public void find(@RequestBody User user){
 ...
}
java 复制代码
@Data
public class User{
  private int id;
  private String name;
  private int age;
}

@RequestBody:将请求中json字符串自动转化为java中的对象。

@ResponseBody: 将控制器方法返回值转为json格式字符串,并相应请求。

相关推荐
随风爱学习16 分钟前
JAVA学习之异常
java
m0_6399069418 分钟前
HashMap:哈希扰动、扩容源码、红黑树转换、并发问题
java·算法·哈希算法
Roll圈圈25 分钟前
长链接太丑影响转化率?这个短链工具让你的推广链接更专业
java
神魔皆以血嗜31 分钟前
Java 存储金额
java·后端
SL_staff1 小时前
周报越厚问题越拖?用结构化执行机制让周报回归决策价值
java·spring cloud·开源
梅梅绵绵冰1 小时前
JVM虚拟机
java·开发语言·jvm
golang学习记2 小时前
Python vs Go:2026年到底该怎么选
java·vscode·python·golang·pycharm·goland
Shaoshing2 小时前
消息顺序
java·开发语言
我命由我123452 小时前
SQL 检测脚本
java·数据库·sql·功能测试·单元测试·压力测试·可用性测试
Hpc_Fun3 小时前
GPU 工作站品牌怎么比?五把可核验尺子、加权评分脚本与场景重排
java·信创·gpu工作站·品牌对比·加权评分