Spring4.3中引进了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping} 来帮助简化常用的HTTP方法的映射 并更好地表达被注解方法的语义。
1.@GetMapping: 处理get请求,传统的RequestMapping来编写应该是@RequestMapping(value = “/get/{id}”, method = RequestMethod.GET)
新方法可以简写为:@GetMapping("/get/{id}"),如判断实体是否存在或查找实体对象。
点击源码查看代码如下:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
method = {RequestMethod.GET}
)
public @interface GetMapping {
@AliasFor(
annotation = RequestMapping.class
)
.......
这里面有声明 ,很明显就是@RequestMapping的注解,并使用 get方法。
到这里几乎就很明显了,GetMapping、PostMapping、PutMapping等注解都是包含@RequestMapping的组合注解,简化了原来的使用方法。
下面这两个是等价的:
@GetMapping(path = "/get")
public String getName() {
return "";
}
@RequestMapping(path = "/get", method = RequestMethod.GET)
public String get() {
return "";
}
2.@PostMapping: 处理post请求,传统的RequestMapping来编写应该是@RequestMapping(value = “/get/{id}”,method = RequestMethod.POST)
新方法可以简写为:@PostMapping("/get/{id}"),
3.@PutMapping: 和PostMapping作用等同,都是用来向服务器提交信息。如果是添加信息,倾向于用@PostMapping,如果是更新信息,倾向于用@PutMapping。两者差别不是很明显。
4.@DeleteMapping 删除URL映射,具体没有再实践中用过,比如用在删除某个或批量实体类。
5.@PatchMapping 用在修改部分字段。也可根据业务应用场景定义成其他功能。
Spinrg官方引进众多请求的原因个人感觉是简化配置。post和get两者的区别如下:
首先,什么情况下是get请求呢:
直接在浏览器地址栏输入某个地址,表单默认的提交方式,什么情况下是post请求呢:
设置表单method = “post”
ajax type: ‘post’,
浏览器通过url处理的请求为get请求,如果后台限制只能用post请求会发生如下错误:
method not allowed, The specified HTTP method is not allowed for the requested resource.
get请求特点:
a. 请求参数会添加到请求资源路径的后面,只能添加少量参数(因为请求行只有一行,大约只能存放2K左右的数据)
b. 请求参数会显示在浏览器地址栏,路由器会记录请求地址 (重要数据不要用此方式传输)
c.如果传输中文,必定会乱码(原因:get请求默认编码格式为:ISO-8859-1,后台编码格式一般为:GBK或者UTF-8)
post请求的特点:
a. 请求参数添加到实体内容里面,可以添加大量的参数(也解释了为什么浏览器地址栏不能发送post请求,在地址栏里我们只能填写URL,并不能进入到Http包的实体当中)
b. 相对安全,但是,post请求不会对请求参数进行加密处理(可以使用https协议来保证数据安全)
要看更深入的HTTP get、post、delete、put介绍查看链接:
https://www.cnblogs.com/JoannaQ/p/3247077.html