各种传参形式

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

相关推荐
qq_2975746714 小时前
【实战教程】SpringBoot 实现多文件批量下载并打包为 ZIP 压缩包
java·spring boot·后端
老毛肚14 小时前
MyBatis插件原理及Spring集成
java·spring·mybatis
学嵌入式的小杨同学14 小时前
【Linux 封神之路】信号编程全解析:从信号基础到 MP3 播放器实战(含核心 API 与避坑指南)
java·linux·c语言·开发语言·vscode·vim·ux
lang2015092814 小时前
JSR-340 :高性能Web开发新标准
java·前端·servlet
Re.不晚14 小时前
Java入门17——异常
java·开发语言
缘空如是14 小时前
基础工具包之JSON 工厂类
java·json·json切换
追逐梦想的张小年15 小时前
JUC编程04
java·idea
好家伙VCC15 小时前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
南极星100515 小时前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言
消失的旧时光-194315 小时前
第十三课:权限系统如何设计?——RBAC 与 Spring Security 架构
java·架构·spring security·rbac