@RequestParam、@RequestBody、@PathVariable
1. @RequestParam
- @RequestParam:get请求时如果用不到它的3个属性,可以省略;其他请求如果是通过param传送数据,必须使用该注释
- 要点:
- 可用于任何类型的请求(get请求数据在请求行中, post请求数据在请求体中)
- 无论时在请求行还是请求体,格式都是:username=zhangsan&password=1234&email=zhangsan@powernode.com
属性
- value: 不解释看代码
- defaultValue :设置默认值
// 发送请求
request.get("/user"{params:{ // 必须使用paramspeopleAge: 20, }
})@GetMapping("/user")
// value属性 :指明发送时url中的名字,和这里的名字做对应,peopleAge对应 age
public String getUser(@RequestParam(value = "peopleAge", defaultValue = "18") int age) {return "Your age is " + age;
}
- required :是否必须传
@GetMapping("/user")
public String getUser(@RequestParam(required = false) String email) {if (email != null) {return "Your email is " + email;} else {return "No email provided.";}
}
2. @RequestBody
- @RequestBody: 最主要的用处,post请求时前端发送json格式字符串,后端用类接收
- 用法
- 可用于非get请求的其他请求
- 前端发送的是json字符串,后端用类接收
- @RequestBody不可以省略
- required属性:是否必需传
@PostMapping("/user/{id}")
public String updateUser(@RequestBody User user) {// 根据id更新用户信息return "User updated successfully.";
}
- 请求
import axios from 'axios';// 假设后端接口地址
const baseUrl = 'http://localhost:8080';// 要发送的数据
const userData = {// 假设User类有name和age属性,根据实际情况修改name: 'John Doe',age: 30
};// 发送POST请求的函数
const sendPostRequest = async () => {try {// 虽然没有在请求头中指明发送的是json格式,只要使用post请求,就会自动对第二个参数进行json格式化const response = await axios.post(`/user`, userData);console.log('请求成功', response.data);} catch (error) {console.error('请求失败', error);}
};// 调用函数发送请求
sendPostRequest();
3. @PathVariable
- @PathVariable:发送Rest风格请求时使用
作用:
- Rest风格请求的占位符
- 可用于任何请求中,get、post、put等等
- 也有required 属性
1. 基本使用
/users/123 //请求的url@GetMapping("/users/{userId}")
public String getUserById(@PathVariable("userId") Long id) {// 根据id从数据库或其他数据源获取用户信息return "User with id " + id + " retrieved successfully.";
}
/orders/100/items/200 // 亲求的url,多个@GetMapping("/orders/{orderId}/items/{itemId}")
public String getOrderItem(@PathVariable("orderId") Long orderId, @PathVariable("itemId") Long itemId) {// 根据orderId和itemId获取订单中的商品信息return "Retrieving item " + itemId + " from order " + orderId;
}
2. 与正则表达式配合使用
@GetMapping("/users/{userId:\\d+}")
public String getUserById(@PathVariable("userId") String userId) {// 这里可以确保userId是数字格式return "User with id " + userId + " retrieved successfully.";
}
4. 遇到的其他情况
特别注意顺序,发送时参数的顺序和接收时参数的顺序
1. get请求发送数据,后端用类接收
- get请求发送了4个参数
request.get("/admin/list",{params:{currentPage:1,pageSize:10,username:"zhangsan",name:"张三",}})
- controller接收
public class AdminController {@GetMapping("/list")public Result<PageResult> getAdminList(// 参数按顺序接收,这里设置了默认值@RequestParam(defaultValue = "1") Integer currentPage,@RequestParam(defaultValue = "10") Integer pageSize,// 第3个和第4个参数赋值给了admin类对象Admin admin) {PageInfo<Admin> adminList = adminService.getAdminList(currentPage, pageSize);return PageResult.ok(adminList);}
}
2. Post请求中@RequestParam和@RequestBody 一起使用
import axios from 'axios';
const baseUrl = 'http://localhost:8080';
const sendPostRequest = async () => {try {const response = await axios.post(`/user`, {// 请求体参数userInfo: {name: 'John Doe',age: 30}}, {// 查询参数params: {id: 123}});console.log('请求成功', response.data);} catch (error) {console.error('请求失败', error);}
};sendPostRequest();
@PostMapping("/user")
public String saveUser(@RequestParam("id") Long id,@RequestBody UserInfo userInfo) {// 保存用户逻辑return "User saved successfully.";
}