@RequestMapping是Spring框架中用于处理HTTP请求的注解之一,用于将请求映射到相应的处理方法。在后续版本的Spring中,@RequestMapping逐渐被更具体的注解所取代,这些注解更清晰地表达了处理方法的用途。以下是一些相关的注解及其简要说明:
-
@RequestMapping(建议使用更具体的注解)
- 用于映射HTTP请求到处理方法。
- 可以用在类级别和方法级别。
- 在类级别时,指定基础路径。
-
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
- 这些注解分别用于处理HTTP的GET、POST、PUT、DELETE、PATCH请求。
- 更具体,更简洁,推荐使用。
@GetMapping("/example") public String handleGetRequest() { // 处理GET请求的方法体 } @PostMapping("/example") public String handlePostRequest() { // 处理POST请求的方法体 } -
@PathVariable
- 用于从URI中提取模板变量,将其作为方法参数。
- 例如,
/users/{userId}中的userId可以通过@PathVariable注解注入到方法参数中。
@GetMapping("/users/{userId}") public String getUserById(@PathVariable Long userId) { // 使用userId处理业务逻辑 } -
@RequestParam
- 用于从请求中提取查询参数,将其作为方法参数。
- 可以指定默认值,是否必需等属性。
@GetMapping("/example") public String handleRequest(@RequestParam(name = "param", defaultValue = "default") String param) { // 处理请求,使用param参数 } -
@RequestBody
- 用于将HTTP请求体映射到方法参数。
- 主要用于接收JSON或XML格式的请求数据。
@PostMapping("/example") public String handlePostRequest(@RequestBody SomeObject requestBody) { // 处理POST请求体中的数据 }