SpringMVC中如何使用@RequestParam和@PathVariable区分GET和POST请求?

@RequestParam注解用于将请求参数绑定到Controller方法的参数上,而@PathVariable注解用于将URI路径变量绑定到Controller方法的参数上。它们都可以用于处理GET和POST请求,但它们的用法略有不同。

使用@RequestParam处理GET请求时,请求参数将附加到请求的查询字符串中,例如:http://example.com/user?id=123。Controller方法需要使用@RequestParam注解声明参数名称和数据类型,以从请求中提取参数值。例如:

@GetMapping("/user")
public String getUserById(@RequestParam("id") Long userId) {
    // do something with userId
}

使用@PathVariable处理GET请求时,请求参数将包含在URL路径中,例如:http://example.com/user/123。Controller方法需要使用@PathVariable注解声明参数名称和数据类型,以从URL路径中提取参数值。例如:

@GetMapping("/user/{id}")
public String getUserById(@PathVariable("id") Long userId) {
    // do something with userId
}

对于处理POST请求,@RequestParam和@PathVariable注解的用法与处理GET请求相同,因为它们都可以从请求正文中提取参数值。例如:

@PostMapping("/user")
public String addUser(@RequestParam("name") String name, @RequestParam("age") Integer age) {
    // do something with name and age
}

@PostMapping("/user/{id}")
public String updateUser(@PathVariable("id") Long userId, @RequestParam("name") String name, @RequestParam("age") Integer age) {
    // do something with userId, name, and age
}