PathVariable和parameter的区别
时间: 2023-12-04 22:41:48 浏览: 19
PathVariable和RequestParam都是Spring MVC中用于接收请求参数的注解,二者的区别如下:
1. @PathVariable用于获取url路径上的参数,而@RequestParam用于获取请求参数中的参数值。
2. @PathVariable注解的参数值可以直接映射到方法的入参中,而@RequestParam需要指定参数名才能将参数值映射到方法的入参中。
3. @PathVariable注解的参数值是必须的,而@RequestParam注解的参数值是可选的,默认值为false。
下面是一个使用@PathVariable和@RequestParam的例子:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
// 根据id查询用户信息
return userService.getUserById(id);
}
@GetMapping("/search")
public List<User> searchUser(@RequestParam String keyword) {
// 根据关键字查询用户信息
return userService.searchUser(keyword);
}
}
```