基本注解
@PathVariable、@RequestHeader、@RequestAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody
这些注解,主要是用在Controller控制器在接收前端传过来的相关请求和数据时使用的。通过这些注解,可以精确的获取相关请求的数据,然后在控制器中处理相关数据。
@PathVariable路径变量:
在rest风格中,可以用@PathVariable注解,对应{id},然后获取请求路径中的变量。
也可以直接获取map,此时就不需要写对应的名称了,直接全部获取到map中,再遍历map即可。
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@PathVariable("id") Integer id,
@PathVariable("username") String name,
@PathVariable Map<String,String> pv){
}
@RequestHeader获取请求头:
网页f12可以看到请求头,请求头中会包含一些属性,可以用@RequestHeader获取相关属性。
也可以直接获取map,此时就不需要写对应的名称了,直接全部获取到map中,再遍历map即可。
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@RequestHeader("User-Agent") String userAgent,
@RequestHeader Map<String,String> header){
}
@RequestParam获取请求参数:
<a href="car/3/?age=18&inter=ball ">
请求中除了有路径遍历,还可以有一些请求参数:?age=18&inter=ball,可以用@RequestParam获取请求参数。
可以获取相关请求名称来获取请求参数,也可以直接获取map。
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar(@RequestParam("age") Integer age,
@RequestParam("inters") List<String> inters,
@RequestParam Map<String,String> params){
}
@CookieValue获取cookie值:
可以获取cookie中的某个值,也可以获取整个Cookie对象。
@GetMapping("/car/{id}/owner/{username}")
public Map<String,Object> getCar( @CookieValue("_ga") String _ga,
@CookieValue("_ga") Cookie cookie){
}
@RequestBody获取请求体:
对于Post请求的form表单,可以用@RequestBody获取请求体。是一个长字符串。
@PostMapping("/save")
public Map postMethod(@RequestBody String content){
Map<String,Object> map = new HashMap<>();
map.put("content",content);
return map;
}
@RequestAttribute获取request域属性:
通常用在页面跳转时,前一个页面通过request.setAttribute(msg,aaa);来传入数据。
跳转后:
1.通过@RequestAttribute(“msg”)String msg;来获取相关信息。
2.因为跳转后也是用一个request对象。因此,也可以通过request.getAttribute(“msg”)来获取。
@MatrixVariable矩阵变量:
其实就是类似于请求参数,只不过是传参是用;分隔开。用于和请求参数区别开来。
/后面第一个参数为路径,路径后面;后面的所有值都是矩阵变量。
1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
2、SpringBoot默认是禁用了矩阵变量的功能
手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
removeSemicolonContent(移除分号内容)支持矩阵变量的
3、矩阵变量必须有url路径变量才能被解析,也就是下面的路径变量不能缺少,不然无法解析矩阵变量。
/cars/{path}、@PathVariable(“path”) String path
@GetMapping("/cars/{path}")
public Map carsSell(@MatrixVariable("low") Integer low,
@MatrixVariable("brand") List<String> brand,
@PathVariable("path") String path){
Map<String,Object> map = new HashMap<>();
map.put("low",low);
map.put("brand",brand);
map.put("path",path);
return map;
}