以前在SpringBoot源码解析-controller层参数的封装 中已经分析过springboot中controller层参数封装的原理,可是工做中毕竟不会一直有时间给你慢慢分析,有时候快速查询也是很必要的。因此今天就总结一下controller层哪些参数封装注解的含义,以及使用,方便之后快速查阅。spring
该注解主要用法有两种,示例以下springboot
http://127.0.0.1:8080/hello?id=123
@GetMapping("hello")
public String hello(@RequestParam("id") String id){
log.info("[{}]",id);
return "hello";
}
id = 123
复制代码
http://127.0.0.1:8080/hello?id=123&name=liuyu
@GetMapping("hello")
public String hello(@RequestParam Map<String,String> value){
System.out.println(value);
return "hello";
}
value = {id=123, name=liuyu}
复制代码
若是咱们想获取所有的get请求值,能够不明确指定RequestParam注解的value,而且使用map来接收参数。这样咱们就能够获得所有的请求值。bash
该注解主要用法有两种,示例以下cookie
http://127.0.0.1:8080/hello/liuyu/qwert
@GetMapping("hello/{id}/{name}")
public String hello(@PathVariable("id") String id,@PathVariable("name") String name){
System.out.println(value);
System.out.println(name);
return "hello";
}
id = liuyu ,name = qwert
复制代码
http://127.0.0.1:8080/hello/liuyu/qwert
@GetMapping("hello/{id}/{name}")
public String hello(@PathVariable Map<String,String> map){
System.out.println(map);
return "hello";
}
map = {id=liuyu, name=qwert}
复制代码
若是要使用该注解须要开启配置session
@Component
public class GlobalWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper=new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
复制代码
该注解主要用法有两种,示例以下app
http://127.0.0.1:8080/hello/liu;value=123
@GetMapping("hello/{id}")
public String hello(@PathVariable(name = "id") String name,@MatrixVariable(name = "value") String value){
System.out.println(name);
System.out.println(value);
return "hello";
}
id = liu
value = 123
复制代码
http://127.0.0.1:8080/hello/liu;value=123;name=qwe
@GetMapping("hello/{id}")
public String hello(@PathVariable(name = "id") String name,@MatrixVariable Map<String,String> value){
System.out.println(name);
System.out.println(value);
return "hello";
}
id = liu
value = {value=123, name=qwe}
复制代码
post 请求,将请具体封装成实体beanide
post请求体
{
"name":"liu",
"id":"123"
}
@PostMapping("hello")
public String hello(@RequestBody User user){
System.out.println(user);
return "hello";
}
user(id=123, name=liu)
复制代码
获取请求头的字段,一样的有获取单个请求头和获取所有请求头的两种用法。post
获取cookie中的键值对的值。ui
请求头添加 Cookie:value=liuyu
@GetMapping("hello")
public String hello(@CookieValue(name = "value") String user){
System.out.println(user);
return "hello";
}
user = liuyu
复制代码
这两个注解功能有点像,一个实在session中寻找相应的对象,一个是在request中找。url