各种传参形式

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

相关推荐
保持学习ing2 分钟前
Spring注解开发
java·深度学习·spring·框架
techzhi3 分钟前
SeaweedFS S3 Spring Boot Starter
java·spring boot·后端
异常君27 分钟前
Spring 中的 FactoryBean 与 BeanFactory:核心概念深度解析
java·spring·面试
weixin_4612594140 分钟前
[C]C语言日志系统宏技巧解析
java·服务器·c语言
cacyiol_Z43 分钟前
在SpringBoot中使用AWS SDK实现邮箱验证码服务
java·spring boot·spring
竹言笙熙1 小时前
Polarctf2025夏季赛 web java ez_check
java·学习·web安全
写bug写bug1 小时前
手把手教你使用JConsole
java·后端·程序员
异常君1 小时前
Java 中 try-catch 的性能真相:全面分析与最佳实践
java·面试·代码规范
程序员清风2 小时前
阿里二面:Kafka 消费者消费消息慢(10 多分钟),会对 Kafka 有什么影响?
java·后端·面试
幼稚园的山代王2 小时前
Prompt Enginering(提示工程)先进技术
java·人工智能·ai·chatgpt·langchain·prompt