Java @RequestMapping 使用案例详解
@RequestMapping 是 Spring MVC 中用于映射 HTTP 请求到控制器方法的注解。

基础配置示例
@RestController
@RequestMapping("/api")
public class UserController {
// 映射 GET 请求
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> getAllUsers() {
return userService.findAll();
}
// 使用简化注解(等价于上面的写法)
@GetMapping("/users")
public List<User> getAllUsers2() {
return userService.findAll();
}
}
完整的 CRUD 案例
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
// 查询所有用户 - GET
@GetMapping
public List<User> list() {
return userService.findAll();
}
// 根据ID查询 - GET
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.findById(id);
}
// 创建用户 - POST
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
// 更新用户 - PUT
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.update(user);
}
// 删除用户 - DELETE
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.deleteById(id);
}
}
路径参数使用
@RestController
@RequestMapping("/api")
public class ProductController {
// 单个路径参数
@GetMapping("/products/{id}")
public Product getProduct(@PathVariable Long id) {
return productService.findById(id);
}
// 多个路径参数
@GetMapping("/categories/{categoryId}/products/{productId}")
public Product getProductByCategory(
@PathVariable Long categoryId,
@PathVariable Long productId) {
return productService.findByCategoryAndId(categoryId, productId);
}
}
请求参数处理
@RestController
@RequestMapping("/api")
public class SearchController {
// 必需参数
@GetMapping("/search")
public List<Product> search(
@RequestParam String keyword,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int size) {
return searchService.search(keyword, page, size);
}
// 可选参数
@GetMapping("/products")
public List<Product> filter(
@RequestParam(required = false) String category,
@RequestParam(required = false) Double minPrice,
@RequestParam(required = false) Double maxPrice) {
return productService.filter(category, minPrice, maxPrice);
}
}
请求映射组合使用
@RestController
public class MultiPathController {
// 映射多个路径
@GetMapping({"/api/users", "/api/customers"})
public List<User> getUsers() {
return userService.findAll();
}
// 映射多个请求方法
@RequestMapping(value = "/data", method = {RequestMethod.GET, RequestMethod.POST})
public String handleData() {
return "Handles both GET and POST";
}
// 使用请求头过滤
@GetMapping(value = "/api/data", headers = "content-type=application/json")
public String handleJsonData() {
return "Only handles JSON content type";
}
}
综合实战案例
@RestController
@RequestMapping("/api/v1")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
// 创建订单
@PostMapping("/orders")
public ResponseEntity<Order> createOrder(@RequestBody @Valid OrderRequest request) {
Order order = orderService.createOrder(request);
return ResponseEntity.status(HttpStatus.CREATED).body(order);
}
// 查询订单列表(带分页)
@GetMapping("/orders")
public ResponseEntity<Page<Order>> listOrders(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String status,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
Pageable pageable = PageRequest.of(page, size);
Page<Order> orders = orderService.findOrders(status, startDate, endDate, pageable);
return ResponseEntity.ok(orders);
}
// 获取订单详情
@GetMapping("/orders/{orderId}")
public ResponseEntity<OrderDetail> getOrderDetail(@PathVariable Long orderId) {
OrderDetail detail = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(detail);
}
// 更新订单状态
@PatchMapping("/orders/{orderId}/status")
public ResponseEntity<Order> updateOrderStatus(
@PathVariable Long orderId,
@RequestBody @Valid StatusUpdateRequest request) {
Order order = orderService.updateStatus(orderId, request.getStatus());
return ResponseEntity.ok(order);
}
// 取消订单
@DeleteMapping("/orders/{orderId}")
public ResponseEntity<Void> cancelOrder(@PathVariable Long orderId) {
orderService.cancelOrder(orderId);
return ResponseEntity.noContent().build();
}
}
配置类示例
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 设置路径匹配后缀
configurer.setUseSuffixPatternMatch(false);
}
}
- 方法级别注解:
@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping是@RequestMapping的简化版本 - 路径变量:使用 定义路径变量,配合
@PathVariable获取 - 请求参数:使用
@RequestParam获取查询参数 - 请求体:使用
@RequestBody获取 POST/PUT 请求体 - 参数验证:配合
@Valid或@Validated进行参数校验
这样你就可以根据实际需求灵活使用 @RequestMapping 及其衍生注解来构建 RESTful API 了。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播