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) {
        // 删除订单
    }
}
相关推荐
不会C语言的男孩4 分钟前
C++ Primer Plus 第8章:函数探幽
开发语言·c++
方也_arkling8 小时前
【Java-Day08】static / final / 枚举
java·开发语言
橙淮8 小时前
Spring Bean作用域与生命周期全解析
java·spring
风吹夏回8 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei118 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1128 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding8 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋99 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
小江的记录本9 小时前
【JVM虚拟机】垃圾回收GC:垃圾收集器:CMS:核心原理、回收流程、优缺点、废弃原因(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·面试·maven
xiaoshuaishuai89 小时前
C# 内存管理与资源泄漏
开发语言·c#