现在controller中有个方法:(LoginUserRequest是一个用户类对象)
java
@PostMapping("/test/phone")
public Result validPhone(LoginUserRequest loginUserRequest) {
return Result.success(loginUserRequest);
}
现在讨论**@Param("loginUserRequest") @RequestParam("loginUserRequest") 和@RequestBody**
三个注解的区别,测试统一用PostMan测试,在博客最后进行总结
一、@Param
++@Param 修饰对象和变量测试一样++
java
@PostMapping("/test/phone")
public Result validPhone(@Param("loginUserRequest") LoginUserRequest loginUserRequest) {
return Result.success(loginUserRequest);
}
使用参数传值:

使用json传值:

二、@RequestParam
++这里使用 @RequestParam 和@RequestParam("loginUserRequest")效果一样++
java
@PostMapping("/test/phone")
public Result validPhone(@RequestParam("loginUserRequest") LoginUserRequest loginUserRequest) {
return Result.success(loginUserRequest);
}
使用参数传值:

使用json传值:

但是我们在参数传值时设置一个变量loginUserRequest,显示参数转换错误,后端把String转为LoginUserRequest对象报错

那我们在json传值时设置一个变量loginUserRequest呢?没报错,但是还是找不到参数

三、@RequestBody
java
@PostMapping("/test/phone")
public Result validPhone(@RequestBody LoginUserRequest loginUserRequest) {
return Result.success(loginUserRequest);
}
使用参数传值:

使用json传值:

如果@RequestBody 是修饰 String phoneNumber 呢?
java
@PostMapping("/test/phone")
public Result validPhoneNumber(@RequestBody String phoneNumber) {
System.out.println("phone = " + phoneNumber);
return Result.success(phoneNumber);
}
使用参数传值和上面的结果一样

使用json传值,会把phoneNumber当做对象


总结:
1.@Param可用来修饰对象和变量,但只能用参数传值,不能用json传值。
2.@RequestParam用来修饰变量,不能修饰对象,只能用参数传值。
2.@RequestBody 修饰的对象,不能修饰变量,只能使用json传值。
此为本人总结,如有错误,恳请指正。