@RequestMapping 注解:

@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。

Request Mapping 基础用法 

在 Spring MVC 应用程序中,RequestDispatcher (在 Front Controller 之下) 这个 servlet 负责将进入的 HTTP 请求路由到控制器的处理方法。 

在对 Spring MVC 进行的配置的时候, 你需要指定请求与处理方法之间的映射关系。

要配置 Web 请求的映射,就需要你用上 @RequestMapping 注解。

@RequestMapping 注解可以在控制器类的级别和/或其中的方法的级别上使用。 

在类的级别上的注解会将一个特定请求或者请求模式映射到一个控制器之上。之后你还可以另外添加方法级别的注解来进一步指定到处理方法的映射关系。 

下面是一个同时在类和方法上应用了 @RequestMapping 注解的示例:

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping("/")
  5. String get() {
  6. //mapped to hostname:port/home/
  7. return "Hello from get";
  8. }
  9. @RequestMapping("/index")
  10. String index() {
  11. //mapped to hostname:port/home/index/
  12. return "Hello from index";
  13. }
  14. }

如上述代码所示,到 /home 的请求会由 get() 方法来处理,而到 /home/index 的请求会由 index() 来处理。

@RequestMapping 来处理多个 URI 

你可以将多个请求映射到一个方法上去,只需要添加一个带有请求路径值列表的 @RequestMapping 注解就行了。

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4.  
  5. @RequestMapping(value = {
  6. "",
  7. "/page",
  8. "page*",
  9. "view/*,**/msg"
  10. })
  11. String indexMultipleMapping() {
  12. return "Hello from index multiple mapping.";
  13. }
  14. }

如你在这段代码中所看到的,@RequestMapping 支持统配符以及ANT风格的路径。前面这段代码中,如下的这些 URL 都会由 indexMultipleMapping() 来处理:

  1. localhost:8080/home
  2. localhost:8080/home/
  3. localhost:8080/home/page
  4. localhost:8080/home/pageabc
  5. localhost:8080/home/view/
  6. localhost:8080/home/view/view

  

@RequestParam

带有 @RequestParam 的 @RequestMapping 

@RequestParam 注解配合 @RequestMapping 一起使用,可以将请求的参数同处理方法的参数绑定在一起。 

@RequestParam 注解使用的时候可以有一个值,也可以没有值。这个值指定了需要被映射到处理方法参数的请求参数, 代码如下所示:

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4.  
  5. @RequestMapping(value = "/id")
  6. String getIdByValue(@RequestParam("id") String personId) {
  7. System.out.println("ID is " + personId);
  8. return "Get ID from query string of URL with value element";
  9. }
  10. @RequestMapping(value = "/personId")
  11. String getId(@RequestParam String personId) {
  12. System.out.println("ID is " + personId);
  13. return "Get ID from query string of URL without value element";
  14. }
  15. }

@RequestParam 的 defaultValue 取值就是用来给取值为空的请求参数提供一个默认值的。

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping(value = "/name")
  5. String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
  6. return "Required element of request param";
  7. }
  8. }

在这段代码中,如果 person 这个请求参数为空,那么 getName() 处理方法就会接收 John 这个默认值作为其参数。

@RequestMapping属性:

method :

Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。 
所有的请求默认都会是 HTTP GET 类型的。

对请求的映射不仅仅不局限在标示的方法的返回值对请求url上,还可以对请求的其属性做出约定,如请求的method,是get还是post。如果做出了method的条件限定,当请求的url即使映射上了,method不符合的话也不能生成物理视图并转发到目标页面。你需要在 @RequestMapping 中使用 method 来声明 HTTP 请求所使用的方法类型:

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping(method = RequestMethod.GET)
  5. String get() {
  6. return "Hello from get";
  7. }
  8. @RequestMapping(method = RequestMethod.DELETE)
  9. String delete() {
  10. return "Hello from delete";
  11. }
  12. @RequestMapping(method = RequestMethod.POST)
  13. String post() {
  14. return "Hello from post";
  15. }
  16. @RequestMapping(method = RequestMethod.PUT)
  17. String put() {
  18. return "Hello from put";
  19. }
  20. @RequestMapping(method = RequestMethod.PATCH)
  21. String patch() {
  22. return "Hello from patch";
  23. }
  24. }

produces:

它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;

  1. @Controller
  2. @RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")
  3. @ResponseBody
  4. public Pet getPet(@PathVariable String petId, Model model) {
  5. // implementation omitted
  6. }

consumes:

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

  1. @Controller
  2. @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
  3. public void addPet(@RequestBody Pet pet, Model model) {
  4. // implementation omitted
  5. }

header:

根据请求中的消息头内容缩小 请求映射 的范围;

  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. public class RelativePathUriTemplateController {
  4.  
  5. @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  6. public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  7. // implementation omitted
  8. }
  9. }
  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping(value = "/head", headers = {
  5. "content-type=text/plain"
  6. })
  7. String post() {
  8. return "Mapping applied along with headers";
  9. }
  10. }
  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping(value = "/head", headers = {
  5. "content-type=text/plain",
  6. "content-type=text/html"
  7. }) String post() {
  8. return "Mapping applied along with headers";
  9. }
  10. }

params :

params 元素可以进一步帮助我们缩小请求映射的定位范围(定义传参的值,当值为定义的值时,进入方法运行,否则不运行)。使用 params 元素,你可以让多个处理方法处理到同一个URL 的请求, 而这些请求的参数是不一样的。你可以用 myParams = myValue 这种格式来定义参数,也可以使用通配符来指定特定的参数值在请求中是不受支持的。

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @RequestMapping(value = "/fetch", params = {
  5. "personId=10"
  6. })
  7. String getParams(@RequestParam("personId") String id) {
  8. return "Fetched parameter using params attribute = " + id;
  9. }
  10. @RequestMapping(value = "/fetch", params = {
  11. "personId=20"
  12. })
  13. String getParamsDifferent(@RequestParam("personId") String id) {
  14. return "Fetched parameter using params attribute = " + id;
  15. }
  16. }

@RequestMapping 快捷方式 :

Spring 4.3 引入了方法级注解的变体,也被叫做 @RequestMapping 的组合注解。组合注解可以更好的表达被注解方法的语义。它们所扮演的角色就是针对 @RequestMapping 的封装,而且成了定义端点的标准方法。 
例如,@GetMapping 是一个组合注解,它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。 
方法级别的注解变体有如下几个:

  1. @GetMapping
  2. @PostMapping
  3. @PutMapping
  4. @DeleteMapping
  5. @PatchMapping

如下代码展示了如何使用组合注解:

  1. @RestController
  2. @RequestMapping("/home")
  3. public class IndexController {
  4. @GetMapping("/person")
  5. public @ResponseBody ResponseEntity < String > getPerson() {
  6. return new ResponseEntity < String > ("Response from GET", HttpStatus.OK);
  7. }
  8. @GetMapping("/person/{id}")
  9. public @ResponseBody ResponseEntity < String > getPersonById(@PathVariable String id) {
  10. return new ResponseEntity < String > ("Response from GET with id " + id, HttpStatus.OK);
  11. }
  12. @PostMapping("/person")
  13. public @ResponseBody ResponseEntity < String > postPerson() {
  14. return new ResponseEntity < String > ("Response from POST method", HttpStatus.OK);
  15. }
  16. @PutMapping("/person")
  17. public @ResponseBody ResponseEntity < String > putPerson() {
  18. return new ResponseEntity < String > ("Response from PUT method", HttpStatus.OK);
  19. }
  20. @DeleteMapping("/person")
  21. public @ResponseBody ResponseEntity < String > deletePerson() {
  22. return new ResponseEntity < String > ("Response from DELETE method", HttpStatus.OK);
  23. }
  24. @PatchMapping("/person")
  25. public @ResponseBody ResponseEntity < String > patchPerson() {
  26. return new ResponseEntity < String > ("Response from PATCH method", HttpStatus.OK);
  27. }
  28. }

在这段代码中,每一个处理方法都使用 @RequestMapping 的组合变体进行了注解。尽管每个变体都可以使用带有方法属性的 @RequestMapping 注解来互换实现, 但组合变体仍然是一种最佳的实践 — 这主要是因为组合注解减少了在应用程序上要配置的元数据,并且代码也更易读。

文章转载至:https://blog.csdn.net/sunshine_yg/article/details/80493604

Springboot:@RequestMapping注解及属性详解的更多相关文章

  1. SPRINGBOOT注解最全详解(

    #     SPRINGBOOT注解最全详解(整合超详细版本)          使用注解的优势:               1.采用纯java代码,不在需要配置繁杂的xml文件           ...

  2. Spring boot注解(annotation)含义详解

    Spring boot注解(annotation)含义详解 @Service用于标注业务层组件@Controller用于标注控制层组件(如struts中的action)@Repository用于标注数 ...

  3. SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解

    SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解 博客分类: 跟开涛学SpringMVC   6.6.2.@RequestParam绑定单个请求参数值 @RequestParam用于 ...

  4. tomcat 三种部署方式以及server.xml文件的几个属性详解

    一.直接将web项目文件件拷贝到webapps目录中 这是最常用的方式,Tomcat的Webapps目录是Tomcat默认的应用目录,当服务器启动时,会加载所有这个目录下的应用.如果你想要修改这个默认 ...

  5. Spring中的@Transactional(rollbackFor = Exception.class)属性详解

    序言 今天我在写代码的时候,看到了.一个注解@Transactional(rollbackFor = Exception.class),今天就和大家分享一下,这个注解的用法: 异常 如下图所示,我们都 ...

  6. @Scheduled注解各参数详解

    @Scheduled注解各参数详解 @Scheduled注解的使用可以参考这个:https://www.cnblogs.com/mengw/p/11564338.html 参数详解 1. cron 该 ...

  7. coding++:Spring中的@Transactional(rollbackFor = Exception.class)属性详解

    异常: 如下图所示,我们都知道 Exception 分为 运行时异常 RuntimeException 和 非运行时异常. error 是一定会回滚的. 如果不对运行时异常进行处理,那么出现运行时异常 ...

  8. android:exported 属性详解

    属性详解 标签: android 2015-06-11 17:47 27940人阅读 评论(7) 收藏 举报 分类: Android(95) 项目点滴(25) 昨天在用360扫描应用漏洞时,扫描结果, ...

  9. OutputCache属性详解(一)一Duration、VaryByParam

    目录 OutputCache概念学习 OutputCache属性详解(一) OutputCache属性详解(二) OutputCache属性详解(三) OutputCache属性详解(四)— SqlD ...

随机推荐

  1. SpringMVC Jackson 库解析 json 串属性名大小写自动转换问题

    问题描述 在项目开发中,当实体类和表中定义的某个字段为 RMBPrice,首字母是大写的,sql 查询出来的列名也是大写的 RMBPrice,但是使用 jquery 的 ajax 返回请求响应时却出错 ...

  2. Oracle和MySQL差异总结

    常用功能差异 锁差异: • Oracle锁加在数据块上 • InnoDB 是在索引上加锁,所以MySQL锁的粒度没有Oracle 精细. 导入导出: • Oracle采用EXP /IMP ,EXPDP ...

  3. CSS(1)基础语法、常见属性

    CSS CSS:层叠样式表.主要用于设置HTML页面中的文本内容(字体.大小.对齐方式等).图片的外形(宽高.边框样式.边距等)以及版面的布局等外观显示样式. CSS语法:CSS实例由选择器,以及一条 ...

  4. unity给子物体添加Shader

    分享两个自制Shader:http://pan.baidu.com/s/1nuRcF2L Shader存放路径:\Assets\Resources\Shader\ 定义Shader类型: public ...

  5. GO语言面向对象04---接口的继承

    package main import "fmt" type Animal interface { Eat(food string) (shit string) GoDie() } ...

  6. kindeditor富文本框使用方法

    这周我一共使用了两个文本框编辑器!我的上一篇文档讲的是wangeditor这个编辑器,现在就来讲讲kindeditor这个编辑器! 首先还是去它的官网去下载脚本! http://kindeditor. ...

  7. OpenCV 查找轮廓

    本文将结合实例代码,介绍 OpenCV 如何查找轮廓.获取边界框. 代码: contours.py OpenCV 提供了 findContours 函数查找轮廓,需要以二值化图像作为输入.并指定些选项 ...

  8. 多目标跟踪:CVPR2019论文阅读

    多目标跟踪:CVPR2019论文阅读 Robust Multi-Modality Multi-Object Tracking  论文链接:https://arxiv.org/abs/1909.0385 ...

  9. sql 数据库使用注意事项

    1.在对数据库表进行操作时,一定要注意当前操作的是哪一个数据库,否则很容易引起不必要的错误.对于master数据库中的数据文件,尽量不要去对其操作. 2.可通过图形方式对数据库进行备份操作,可通过数据 ...

  10. 狂神说Linux笔记:Vim和账号、用户组、磁盘管理

    什么是Vim编辑器 Vim是从 vi 发展出来的一个文本编辑器.代码补完.编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用. 简单的来说, vi 是老式的字处理器,不过功能已经很齐全了,但 ...