Spring MVC之@RequestMapping 详解
2026/9/4 10:20:30 网站建设 项目流程

引言

前段时间项目中用到了 REST 风格来开发程序,但是当用 POST、PUT 模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没有加任何注解)。查看了提交方式为 application/json,而且服务器端通过 request.getReader() 打出的数据里确实存在浏览器提交的数据。为了找出原因,便对参数绑定(@RequestParam、@RequestBody、@RequestHeader、@PathVariable)进行了研究,同时也看了一下 HttpMessageConverter 的相关内容,在此一并总结。

一、@RequestMapping 注解简介

@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping 注解有六个属性,下面我们将其分成三类进行说明。

1.1 value 与 method

value:指定请求的实际地址,指定的地址可以是 URI Template 模式(后面将会说明)。

method:指定请求的 method 类型,如 GET、POST、PUT、DELETE 等。

1.2 consumes 与 produces

consumes:指定处理请求的提交内容类型(Content-Type),例如 application/json、text/html。

produces:指定返回的内容类型,仅当 request 请求头中的 Accept 类型中包含该指定类型才返回。

1.3 params 与 headers

params:指定 request 中必须包含某些参数值,才让该方法处理。

headers:指定 request 中必须包含某些指定的 header 值,才能让该方法处理请求。

二、@RequestMapping 使用示例

2.1 value 与 method 示例

默认@RequestMapping("...str...")即为 value 的值。

value 的 URI 值可以分为以下三类:

  • A)普通的具体值
  • B)含有路径变量的 URI 模板模式(URI Template Patterns with Path Variables)
  • C)含正则表达式的 URI 模板模式(URI Template Patterns with Regular Expressions)
示例 A:类级别与多个方法映射
@Controller @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; @Autowired public AppointmentsController(AppointmentBook appointmentBook) { this.appointmentBook = appointmentBook; } @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(value="/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } @RequestMapping(method = RequestMethod.POST) public String add(@Valid AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } }
示例 B:路径变量(Path Variables)
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable String ownerId, Model model) { Owner owner = ownerService.findOwner(ownerId); model.addAttribute("owner", owner); return "displayOwner"; }
示例 C:正则表达式路径变量
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}.{extension:\\.[a-z]}") public void handle(@PathVariable String version, @PathVariable String extension) { // ... }

2.2 consumes 与 produces 示例

consumes 示例:限制请求 Content-Type
@Controller @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json") public void addPet(@RequestBody Pet pet, Model model) { // implementation omitted }

该方法仅处理 request Content-Type 为 "application/json" 类型的请求。

produces 示例:限制响应 Accept 类型
@Controller @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json") @ResponseBody public Pet getPet(@PathVariable String petId, Model model) { // implementation omitted }

该方法仅处理 request 请求中 Accept 头中包含了 "application/json" 的请求,同时暗示了返回的内容类型为 application/json。

2.3 params 与 headers 示例

params 示例:限制请求参数
@Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } }

仅处理请求中包含了名为 "myParam",值为 "myValue" 的请求。

headers 示例:限制请求头
@Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } }

仅处理 request 的 header 中包含了指定 "Referer" 请求头和对应值为 "http://www.ifeng.com/" 的请求。

总结

本文介绍了 Spring MVC 中 @RequestMapping 注解的六个属性及其分类,并通过具体示例展示了 value、method、consumes、produces、params 和 headers 的用法。这些属性可以帮助我们更精确地控制请求的映射条件。

上面仅仅介绍了 @RequestMapping 指定的方法处理哪些请求,下一篇将讲解怎样处理 request 提交的数据(数据绑定)和返回的数据。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询