day7 关于请求注解
1. 普通参数与基本注解
-
注解
// 示例 @RequestMapping("/hello") public String hello(@RequestParam("username") String name){ return "aaa"; }
-
Servlet Api
@RequestMapping("/hello") public String hello(HttpSession httpSession){ return "aaa"; }
-
负责参数
@RequestMapping("/hello") public String hello(Model model){ // request return "aaa"; }
-
自定义类型的参数对象
@RequestMapping("/hello") public String hello(Person person){ return "aaa"; }
@RestController
public class ParameterTestController{
@GetMapping("car/{id}/{username}")
public Map<String,obect> getCar(@PathVariable("id") Integer id,
@PathVariable("username") String name,
@PathVariable Map<String,String> pv,
@RequestHeader("User-Agent") String userAgent,
@RequestHeader Map<String,String> header,
@RequestParam("age") Integer age,
@RequestParam Map<String,String> params,
@CookieValue("cookie") String cookie,
@CookieValue("cookie") Cookie cookieInfo){
Map<String,object> map = new HashMap<>();
map.put("id",id);
map.put("name",name);
map.put("pv",pv);
map.put("userAgent",useragent);
map.put("header",header);
return map;
}
}
// 获取请求体
@PostMapping("/save")
public Map postMethod(@RequestBody String content){
Map<String,object> map = new HashMap<>();
map.put("content",content);
return map;
}
关于 @RequestAttribute
@Controller
public class RequestController{
@GetMapping("/goto")
public String goTOPage(HttpServletRequest req){
req.setAttribute("msg","ok");
return "forward:/success"; // 转发到 /success 请求
}
@GetMapping("/success")
@ResponseBody
public Map success(@RequestAttribute("msg") String msg,
HttpServletRequest req){
Object msgInfo = req.getAttribute("msg");
Map<String,object> map = new HashMap<>();
map.put("req.get",msgInfo);
map.put("annotation_msg",msg);
return map;
}
}
关于 @MatrixVariable 矩阵变量
/user/1;age=10;d=20 矩阵变量,路径重写,使用矩阵变量注解获取值。
@Controller
public class RequestController{
// 1.语法:/user/1;age=10;day=20
// 2.springboot 默认禁用矩阵变量的功能。
// 手动开启:原理,对于路径的处理,UrlPathHelper 进行解析
// removeSemicolonContent (移除分号内容) 支持矩阵变量
// 3.矩阵变量必须有 url 路径变量才能被解析
@GetMapping("/success/{path}")
@ResponseBody
public Map success(@MatrixVariable("age") Integer age,
@MatrixVariable("day") Integer day){
Map<String,object> map = new HashMap<>();
map.put("age",age);
return map;
}
}
@UrlPathHelper
2. Servlet Api
WebRequest , ServletRequest , MultipartRequest , HttpSession , javax.servlet.http.PushBuilder , Principal , InputStream , Reader , HttpMethod , Locale , TimeZone , ZoneId
ServletRequestMethodArgumentResolver 可以解析以上的部分参数
3. 复杂参数
Map , Errors/BindingResult , Model , RedirectAttributes , ServletResponse , SessionStatus , UriComponentsBuilder , ServletURiComponentsBuilder
Map、Model(map、model里面的数据会被放在request的请求域, request.setAttribute)
RedirectAttributes(重定向携带数据)
ServletResponse(response)
Map、Model类型的参数,会返回 mavContainer.getModel() —> BindingAwareModelMap 是 Model 也是 Map
4. 自定义对象参数
可以自动类型转换和格式化,可以级联封装