SpringMVC核心注解:@RequestMapping详解

概述

@RequestMapping是SpringMVC中最核心的注解之一,用于将HTTP请求映射到MVC和REST控制器的处理方法上。

基本功能

@RequestMapping主要用于:

  • 映射URL到控制器类或方法
  • 定义请求方法类型(GET、POST等)
  • 定义请求参数、请求头等条件

使用位置

类级别:定义基本请求路径

java 复制代码
@RequestMapping("/order")
@Controller
public class OrderController {
    // ...
}

方法级别:定义具体路径和请求方法

java 复制代码
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
@ResponseBody
public List<Order> findAll() {
    // ...
}

主要属性

属性名 说明 示例
value/path 映射的URL路径 @RequestMapping("/orders")
method 请求方法类型 method = RequestMethod.GET
params 请求方法参数 params = "type=book"
headers 请求头条件 headers = "content-type=text/*"
consumes 请求内容类型 consumes = "application/json"
produces 响应内容类型 produces = "application/json"

常见组合注解

Spring 4.3+ 提供了更简洁的派生注解代码

注解 等价于
@GetMapping @RequestMapping(method = RequestMethod.GET)
@PostMapping @RequestMapping(method = RequestMethod.POST)
@PutMapping @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping @RequestMapping(method = RequestMethod.PATCH)

路径变量

可以与@PathVariable配合使用

java 复制代码
@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {
    // ...
}

示例代码

java 复制代码
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @GetMapping
    public List<Order> getAll() {
        // 获取所有订单
    }

    @GetMapping("/{id}")
    public Order getById(@PathVariable Long id) {
        // 获取特定ID的订单
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Order create(@RequestBody Order order) {
        // 创建新订单
    }

    @PutMapping("/{id}")
    public Order update(@PathVariable Long id, @RequestBody Order order) {
        // 更新订单
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        // 删除订单
    }
}
相关推荐
aqiu11111118 分钟前
【C++算法打怪专栏】8. 字符串转换整数 (atoi)
开发语言·c++·算法
爱吃香菜的初学者25 分钟前
十四.Linux——消息队列
linux·运维·开发语言
迅猛龙办公室40 分钟前
python实现倒序输出数字
开发语言·python
夏幻灵7 小时前
JavaScript this 面试:五种绑定规则、优先级与常见面试陷阱
开发语言·javascript·面试
程序猿编码7 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
bkspiderx8 小时前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
代码什么用8 小时前
Spring基础使用
java·后端·spring
程序员老陆8 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光9 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
Su米苏9 小时前
Spring AI 中MCP 与普通 @Tool的区别
java·人工智能·spring