基本注解
@PathVariable(获取路径变量)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基本注解测试</title>
</head>
<body>
测试基本注解:
<ul>
<li>@PathVariable(路径变量):<a href="user/3/pet/tom">user/3/pet/tom</a></li>
<li>@RequestParam(获取请求参数)</li>
<li>@RequestHeader(获取请求头)</li>
<li>@CookieValue(获取cookie值)</li>
<li>@RequestBody(获取请求体[POST])</li>
</ul>
</body>
</html>
ParameterTestController类:
@RestController
public class ParameterTestController {
@GetMapping("user/{id}/pet/{petName}")//映射html中的链接地址——href="user/3/pet/tom"
public Map<String,Object> getUser(@PathVariable() String id,//获取路径变量id的值
@PathVariable() String petName,
@PathVariable Map<String,String> pv){//获取链接中全部路径变量
Map<String,Object> map=new HashMap<>();
map.put("id",id);
map.put("petName",petName);
map.put("pv",pv);
return map;
}
}
结果:
@RequestParam(获取请求参数)
index.html
@RequestParam(获取请求参数)<a href="user/zhangsan?age=18&interests=basketball&interests=game">user/zhangsan?age=18&interests=basketball&interests=game</a>
ParameterTestController类添加:
@GetMapping("user/zhangsan")//映射html中的链接地址——href="user/zhangsan?age=18&interests=basketball&interests=game"
public Map<String,Object> getUser2(@RequestParam("age") Integer age,
@RequestParam("interests") List<String> interests,
@RequestParam Map<String,String> params){
Map<String,Object> map2=new HashMap<>();
map2.put("age",age);
map2.put("interests",interests);
map2.put("params",params);
return map2;
}
结果:
@RequestHeader(获取请求头)
index. html:
@RequestHeader(获取请求头)<a href="user/RequestHeader">user/RequestHeader</a>
ParameterTestController类添加:
@GetMapping("user/RequestHeader")
public Map<String,Object> getUser3(@RequestHeader("Accept") String Accept,
@RequestHeader Map<String,String> header){
Map<String,Object> map=new HashMap<>();
map.put("Accept",Accept);
map.put("header",header);
return map;
结果:
@RequestBody(获取请求体[POST])
index.html
<form action="/save" method="post">
测试@RequestBody获取数据 <br/>
用户名:<input name="userName"/> <br>
邮箱:<input name="email"/>
<input type="submit" value="提交"/>
</form>
ParameterTestController类添加:
@PostMapping("/save")
public Map postMethod(@RequestBody String content){
Map<String,Object> map = new HashMap<>();
map.put("content",content);
return map;
}
结果: