概述
之前的文章springmvc使用注解声明控制器与请求映射有简单提到过控制器与请求映射,这一次就详细讲解一下SpringMVC
的REST
风格的四种请求方式及其使用方法。
你能get的知识点
1、什么是Rest风格?
2、基于springmvc
实现REST风格的四种请求方式
3、post请求转换为delete
与put
请求
4、解决请求乱码问题
5、RequestMapping
注解的属性
文章目录
壹:rest风格
一:什么是Rest风格?
REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。
简单来说:使用URL定位资源,用HTTP动词(例如GET,POST,DELETE,DETC等)描述操作。
二:REST风格的四种请求方式
请求 | 说明 | 用于 | 例子 | 例子说明 |
---|---|---|---|---|
@GetMapping | 匹配GET方式的请求; | 一般用于读取数据 | /user/1 | 获取一号用户信息 |
@PostMapping | 匹配POST方式的请求; | 一般用于新增数据 | /user/1 | 新增一号用户 |
@PutMapping | 匹配PUT方式的请求; | 一般用于更新数据 | /user/1 | 修改一号用户 |
@DeleteMapping | 匹配DELETE方式的请求; | 一般用于删除数据 | /user/1 | 删除一号用户 |
也就是说,我们不再使用/user/getuser?user=1
、/user/deleteuser?user=1
等来区分使用者的行为操作,而是使用不同的请求方式来描述行为。
贰:基于springmvc
实现REST风格的四种请求方式
Spring框架的4.3版本后,引入了新的组合注解,来帮助简化常用的HTTP
方法的映射,并更好的表达被注解方法的语义。
@GetMapping = @requestMapping(method = RequestMethod.GET)。
@PostMapping = @requestMapping(method = RequestMethod.POST)。
@DeleteMapping = @requestMapping(method = RequestMethod.DELETE)。
@PutMapping = @requestMapping(method = RequestMethod.PuT)。
一:@GetMapping请求
以@GetMapping
为例,该组合注解是@RequestMapping(method = RequestMethod.GET)
的缩写,它会将HTTP GET请求映射到特定的处理方法上。
RequestMapping
后所有属性都是可选的,但其默认属性是value
。当value
是其唯一属性时,可以省略属性名。
@RequestMapping(value = "/rest",method = RequestMethod.GET)
public String restGet(){
System.out.println("Get请求,hello.....");
return "hello";
}
@GetMapping
是一个组合注解,是@RequestMapping(method = RequestMethod.GET)
的缩写。
所以我们可以将以上代码简单的写成:
@GetMapping("/rest")
public String restGet(){
System.out.println("Get请求,hello.....");
return "hello";