SpringBoot2路由与请求映射

路由与请求映射

在 Spring Boot 中,路由与请求映射是处理 HTTP 请求的核心机制。通过不同的注解,可以将特定的请求路径映射到控制器中的方法,从而实现 RESTful API 的功能。以下是对这部分的详细讲解。

1. 请求映射基础

基础概念:

  • 请求映射: 将 HTTP 请求(如 GET、POST 等)映射到控制器的方法上。每个方法可以处理特定的请求路径和请求方式。
  • 路由: HTTP 请求的 URL 路径,通常以特定的模式定义。

2. 常用注解

Spring 提供了一些专用的注解来处理不同的 HTTP 方法。以下是常用的请求映射注解:

@RequestMapping
  • 用途: 用于定义请求的基本映射,可以处理各种 HTTP 请求方法(GET、POST、PUT、DELETE 等)。
  • 用法: 可以用于类和方法上,支持 URI 模板、请求参数、请求头等。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

@RequestMapping(method = RequestMethod.GET)
public List<User> getAllUsers() {
return userService.findAllUsers();
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUserById(@PathVariable Long id) {
return userService.findUserById(id);
}
}
@GetMapping
  • 用途: 简化了 @RequestMapping(method = RequestMethod.GET) 的写法,只处理 GET 请求。
  • 用法: 通常用于获取资源。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

@GetMapping
public List<User> getAllUsers() {
return userService.findAllUsers();
}
}
@PostMapping
  • 用途: 简化了 @RequestMapping(method = RequestMethod.POST) 的写法,只处理 POST 请求。
  • 用法: 通常用于创建资源。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
@PutMapping
  • 用途: 简化了 @RequestMapping(method = RequestMethod.PUT) 的写法,只处理 PUT 请求。
  • 用法: 通常用于更新资源。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}
}
@DeleteMapping
  • 用途: 简化了 @RequestMapping(method = RequestMethod.DELETE) 的写法,只处理 DELETE 请求。
  • 用法: 通常用于删除资源。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}

3. 路径变量和请求参数

路径变量
  • 用途: 用于在请求 URL 中提取动态参数。
  • 用法: 使用 @PathVariable 注解来接收路径中的变量。

示例:

1
2
3
4
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findUserById(id);
}
  • 请求示例:GET /api/users/1,将把 1 作为 id 传递给方法。
请求参数
  • 用途: 用于从请求 URL 中提取查询参数。
  • 用法: 使用 @RequestParam 注解接收请求参数。

示例:

1
2
3
4
@GetMapping
public List<User> getUsersByName(@RequestParam String name) {
return userService.findUsersByName(name);
}
  • 请求示例:GET /api/users?name=John,将把 name 的值传递给方法。

4. 请求头和请求体

请求头
  • 用途: 用于从请求中提取头信息。
  • 用法: 使用 @RequestHeader 注解接收请求头。

示例:

1
2
3
4
5
@GetMapping
public List<User> getUsers(@RequestHeader("Authorization") String authHeader) {
// 使用 authHeader 进行验证
return userService.findAllUsers();
}
请求体
  • 用途: 用于从请求中提取 JSON 或其他格式的数据。
  • 用法: 使用 @RequestBody 注解将请求体映射到 Java 对象。

示例:

1
2
3
4
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}

5. 响应处理

在 Spring Boot 中,控制器方法的返回值将自动序列化为 JSON 格式并返回给客户端。您可以通过以下方式控制响应:

  • 使用 ResponseEntity 返回更复杂的响应,例如设置 HTTP 状态码、头信息等。

示例:

1
2
3
4
5
6
7
import org.springframework.http.ResponseEntity;

@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
}

6. 全局异常处理

为了处理在控制器中可能出现的异常,可以使用 @ControllerAdvice 来实现全局异常处理。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}

总结

路由与请求映射是 Spring Boot 核心功能之一,通过不同的注解(如 @GetMapping@PostMapping 等),我们可以轻松地将 HTTP 请求映射到控制器方法。结合路径变量、请求参数、请求头和请求体等特性,我们可以处理各种复杂的请求场景。同时,通过响应处理和异常处理机制,我们可以增强 API 的健壮性和可用性。