Springboot:@RequestMapping注解及属性详解
@RequestMapping 注解:
@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
Request Mapping 基础用法
在 Spring MVC 应用程序中,RequestDispatcher (在 Front Controller 之下) 这个 servlet 负责将进入的 HTTP 请求路由到控制器的处理方法。
在对 Spring MVC 进行的配置的时候, 你需要指定请求与处理方法之间的映射关系。
要配置 Web 请求的映射,就需要你用上 @RequestMapping 注解。
@RequestMapping 注解可以在控制器类的级别和/或其中的方法的级别上使用。
在类的级别上的注解会将一个特定请求或者请求模式映射到一个控制器之上。之后你还可以另外添加方法级别的注解来进一步指定到处理方法的映射关系。
下面是一个同时在类和方法上应用了 @RequestMapping 注解的示例:
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping("/")
- String get() {
- //mapped to hostname:port/home/
- return "Hello from get";
- }
- @RequestMapping("/index")
- String index() {
- //mapped to hostname:port/home/index/
- return "Hello from index";
- }
- }
如上述代码所示,到 /home 的请求会由 get() 方法来处理,而到 /home/index 的请求会由 index() 来处理。
@RequestMapping 来处理多个 URI
你可以将多个请求映射到一个方法上去,只需要添加一个带有请求路径值列表的 @RequestMapping 注解就行了。
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = {
- "",
- "/page",
- "page*",
- "view/*,**/msg"
- })
- String indexMultipleMapping() {
- return "Hello from index multiple mapping.";
- }
- }
如你在这段代码中所看到的,@RequestMapping 支持统配符以及ANT风格的路径。前面这段代码中,如下的这些 URL 都会由 indexMultipleMapping() 来处理:
- localhost:8080/home
- localhost:8080/home/
- localhost:8080/home/page
- localhost:8080/home/pageabc
- localhost:8080/home/view/
- localhost:8080/home/view/view
@RequestParam
带有 @RequestParam 的 @RequestMapping
@RequestParam 注解配合 @RequestMapping 一起使用,可以将请求的参数同处理方法的参数绑定在一起。
@RequestParam 注解使用的时候可以有一个值,也可以没有值。这个值指定了需要被映射到处理方法参数的请求参数, 代码如下所示:
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = "/id")
- String getIdByValue(@RequestParam("id") String personId) {
- System.out.println("ID is " + personId);
- return "Get ID from query string of URL with value element";
- }
- @RequestMapping(value = "/personId")
- String getId(@RequestParam String personId) {
- System.out.println("ID is " + personId);
- return "Get ID from query string of URL without value element";
- }
- }
@RequestParam 的 defaultValue 取值就是用来给取值为空的请求参数提供一个默认值的。
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = "/name")
- String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
- return "Required element of request param";
- }
- }
在这段代码中,如果 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 请求所使用的方法类型:
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(method = RequestMethod.GET)
- String get() {
- return "Hello from get";
- }
- @RequestMapping(method = RequestMethod.DELETE)
- String delete() {
- return "Hello from delete";
- }
- @RequestMapping(method = RequestMethod.POST)
- String post() {
- return "Hello from post";
- }
- @RequestMapping(method = RequestMethod.PUT)
- String put() {
- return "Hello from put";
- }
- @RequestMapping(method = RequestMethod.PATCH)
- String patch() {
- return "Hello from patch";
- }
- }
produces:
它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;
- @Controller
- @RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")
- @ResponseBody
- public Pet getPet(@PathVariable String petId, Model model) {
- // implementation omitted
- }
consumes:
指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
- @Controller
- @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
- public void addPet(@RequestBody Pet pet, Model model) {
- // implementation omitted
- }
header:
根据请求中的消息头内容缩小 请求映射 的范围;
- @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
- }
- }
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = "/head", headers = {
- "content-type=text/plain"
- })
- String post() {
- return "Mapping applied along with headers";
- }
- }
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = "/head", headers = {
- "content-type=text/plain",
- "content-type=text/html"
- }) String post() {
- return "Mapping applied along with headers";
- }
- }
params :
params 元素可以进一步帮助我们缩小请求映射的定位范围(定义传参的值,当值为定义的值时,进入方法运行,否则不运行)。使用 params 元素,你可以让多个处理方法处理到同一个URL 的请求, 而这些请求的参数是不一样的。你可以用 myParams = myValue 这种格式来定义参数,也可以使用通配符来指定特定的参数值在请求中是不受支持的。
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @RequestMapping(value = "/fetch", params = {
- "personId=10"
- })
- String getParams(@RequestParam("personId") String id) {
- return "Fetched parameter using params attribute = " + id;
- }
- @RequestMapping(value = "/fetch", params = {
- "personId=20"
- })
- String getParamsDifferent(@RequestParam("personId") String id) {
- return "Fetched parameter using params attribute = " + id;
- }
- }
@RequestMapping 快捷方式 :
Spring 4.3 引入了方法级注解的变体,也被叫做 @RequestMapping 的组合注解。组合注解可以更好的表达被注解方法的语义。它们所扮演的角色就是针对 @RequestMapping 的封装,而且成了定义端点的标准方法。
例如,@GetMapping 是一个组合注解,它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。
方法级别的注解变体有如下几个:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
如下代码展示了如何使用组合注解:
- @RestController
- @RequestMapping("/home")
- public class IndexController {
- @GetMapping("/person")
- public @ResponseBody ResponseEntity < String > getPerson() {
- return new ResponseEntity < String > ("Response from GET", HttpStatus.OK);
- }
- @GetMapping("/person/{id}")
- public @ResponseBody ResponseEntity < String > getPersonById(@PathVariable String id) {
- return new ResponseEntity < String > ("Response from GET with id " + id, HttpStatus.OK);
- }
- @PostMapping("/person")
- public @ResponseBody ResponseEntity < String > postPerson() {
- return new ResponseEntity < String > ("Response from POST method", HttpStatus.OK);
- }
- @PutMapping("/person")
- public @ResponseBody ResponseEntity < String > putPerson() {
- return new ResponseEntity < String > ("Response from PUT method", HttpStatus.OK);
- }
- @DeleteMapping("/person")
- public @ResponseBody ResponseEntity < String > deletePerson() {
- return new ResponseEntity < String > ("Response from DELETE method", HttpStatus.OK);
- }
- @PatchMapping("/person")
- public @ResponseBody ResponseEntity < String > patchPerson() {
- return new ResponseEntity < String > ("Response from PATCH method", HttpStatus.OK);
- }
- }
在这段代码中,每一个处理方法都使用 @RequestMapping 的组合变体进行了注解。尽管每个变体都可以使用带有方法属性的 @RequestMapping 注解来互换实现, 但组合变体仍然是一种最佳的实践 — 这主要是因为组合注解减少了在应用程序上要配置的元数据,并且代码也更易读。
文章转载至:https://blog.csdn.net/sunshine_yg/article/details/80493604
Springboot:@RequestMapping注解及属性详解的更多相关文章
- SPRINGBOOT注解最全详解(
# SPRINGBOOT注解最全详解(整合超详细版本) 使用注解的优势: 1.采用纯java代码,不在需要配置繁杂的xml文件 ...
- Spring boot注解(annotation)含义详解
Spring boot注解(annotation)含义详解 @Service用于标注业务层组件@Controller用于标注控制层组件(如struts中的action)@Repository用于标注数 ...
- SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解
SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解 博客分类: 跟开涛学SpringMVC 6.6.2.@RequestParam绑定单个请求参数值 @RequestParam用于 ...
- tomcat 三种部署方式以及server.xml文件的几个属性详解
一.直接将web项目文件件拷贝到webapps目录中 这是最常用的方式,Tomcat的Webapps目录是Tomcat默认的应用目录,当服务器启动时,会加载所有这个目录下的应用.如果你想要修改这个默认 ...
- Spring中的@Transactional(rollbackFor = Exception.class)属性详解
序言 今天我在写代码的时候,看到了.一个注解@Transactional(rollbackFor = Exception.class),今天就和大家分享一下,这个注解的用法: 异常 如下图所示,我们都 ...
- @Scheduled注解各参数详解
@Scheduled注解各参数详解 @Scheduled注解的使用可以参考这个:https://www.cnblogs.com/mengw/p/11564338.html 参数详解 1. cron 该 ...
- coding++:Spring中的@Transactional(rollbackFor = Exception.class)属性详解
异常: 如下图所示,我们都知道 Exception 分为 运行时异常 RuntimeException 和 非运行时异常. error 是一定会回滚的. 如果不对运行时异常进行处理,那么出现运行时异常 ...
- android:exported 属性详解
属性详解 标签: android 2015-06-11 17:47 27940人阅读 评论(7) 收藏 举报 分类: Android(95) 项目点滴(25) 昨天在用360扫描应用漏洞时,扫描结果, ...
- OutputCache属性详解(一)一Duration、VaryByParam
目录 OutputCache概念学习 OutputCache属性详解(一) OutputCache属性详解(二) OutputCache属性详解(三) OutputCache属性详解(四)— SqlD ...
随机推荐
- SpringMVC Jackson 库解析 json 串属性名大小写自动转换问题
问题描述 在项目开发中,当实体类和表中定义的某个字段为 RMBPrice,首字母是大写的,sql 查询出来的列名也是大写的 RMBPrice,但是使用 jquery 的 ajax 返回请求响应时却出错 ...
- Oracle和MySQL差异总结
常用功能差异 锁差异: • Oracle锁加在数据块上 • InnoDB 是在索引上加锁,所以MySQL锁的粒度没有Oracle 精细. 导入导出: • Oracle采用EXP /IMP ,EXPDP ...
- CSS(1)基础语法、常见属性
CSS CSS:层叠样式表.主要用于设置HTML页面中的文本内容(字体.大小.对齐方式等).图片的外形(宽高.边框样式.边距等)以及版面的布局等外观显示样式. CSS语法:CSS实例由选择器,以及一条 ...
- unity给子物体添加Shader
分享两个自制Shader:http://pan.baidu.com/s/1nuRcF2L Shader存放路径:\Assets\Resources\Shader\ 定义Shader类型: public ...
- GO语言面向对象04---接口的继承
package main import "fmt" type Animal interface { Eat(food string) (shit string) GoDie() } ...
- kindeditor富文本框使用方法
这周我一共使用了两个文本框编辑器!我的上一篇文档讲的是wangeditor这个编辑器,现在就来讲讲kindeditor这个编辑器! 首先还是去它的官网去下载脚本! http://kindeditor. ...
- OpenCV 查找轮廓
本文将结合实例代码,介绍 OpenCV 如何查找轮廓.获取边界框. 代码: contours.py OpenCV 提供了 findContours 函数查找轮廓,需要以二值化图像作为输入.并指定些选项 ...
- 多目标跟踪:CVPR2019论文阅读
多目标跟踪:CVPR2019论文阅读 Robust Multi-Modality Multi-Object Tracking 论文链接:https://arxiv.org/abs/1909.0385 ...
- sql 数据库使用注意事项
1.在对数据库表进行操作时,一定要注意当前操作的是哪一个数据库,否则很容易引起不必要的错误.对于master数据库中的数据文件,尽量不要去对其操作. 2.可通过图形方式对数据库进行备份操作,可通过数据 ...
- 狂神说Linux笔记:Vim和账号、用户组、磁盘管理
什么是Vim编辑器 Vim是从 vi 发展出来的一个文本编辑器.代码补完.编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用. 简单的来说, vi 是老式的字处理器,不过功能已经很齐全了,但 ...