记录一下前后端传递参数的几种方式
第一种 QueryString方式
URL :http://localhost:8989/findById?id=21
对应后端controller层代码
@GetMapping("/findById")
public AjaxResult findById(String id){
System.out.println(id);
return AjaxResult.success();
}
第二种 路经传参
URL: http://localhost:8989/findById/21
对应后端controller层代码
@GetMapping("/findById/{id}")
public AjaxResult findById(@PathVariable("id") String id){
System.out.println(id);
return AjaxResult.success();
}
第三种 传递JSON格式字符串
前端axio请求
axio({
url: 'http://localhost:8989/find',
method: 'post',
data: {
id:21,
name:'zyffff'
}
})
注意:请求头的 content-type 应该为 application/json
后端User实体类
public class User{
private Long id;
private String name;
}
对应后端controller层代码
@PostMapping("/find")
public AjaxResult find(@RequestBody User user){
System.out.println(user);
return AjaxResult.success();
}
@ResponseBody:将控制器方法返回值转为json格式的字符串 并响应请求
@RequestBody: 将请求中的json格式字符串自动转换成java中的对象
第四种 Form表单方式
<form action="http://localhost:8989/find" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit"/>
</form>
对应后端controller层代码
@PostMapping("/find")
public AjaxResult find(User user){
System.out.println(user);
return AjaxResult.success();
}
// 或者
@PostMapping("/find")
public AjaxResult find(Long id, String name){
System.out.println(id);
System.out.println(name);
return AjaxResult.success();
}
这种方式还可以提交文件
<form action="http://localhost:8989/upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo"/>
<input type="submit"/>
</form>
注意:请求头的 content-type 应该为 multipart/form-data
@PostMapping("/upload")
public AjaxResult upload(MultipartFile photo){
// MultipartFile 可转化成 InputStream, 然后可按照java的IO处理方式进行处理
return AjaxResult.success();
}