各种传参形式

一、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格式字符串,并相应请求。

相关推荐
渣哥几秒前
ElasticSearch深度分页的致命缺陷,千万数据查询秒变蜗牛
java
Olrookie1 分钟前
XXL-JOB GLUE模式动态数据源实践:Spring AOP + MyBatis 解耦多库查询
java·数据库·spring boot
柯南二号18 分钟前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
又是努力搬砖的一年27 分钟前
SpringBoot中,接口加解密
java·spring boot·后端
:-)29 分钟前
idea配置maven国内镜像
java·ide·maven·intellij-idea
啊阿狸不会拉杆1 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
用户802973565411 小时前
【水平:编写简单的SpringCloud】用一篇文章精通SpringCloud-1
java
蔡俊锋1 小时前
Javar如何用RabbitMQ订单超时处理
java·python·rabbitmq·ruby
天天摸鱼的java工程师2 小时前
Snowflake 雪花算法优缺点(Java老司机实战总结)
java·后端·面试
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 11: 寻找峰值、山脉数组的峰顶索引
java·算法·leetcode