文章目录
- 1. 直接把请求参数写在方法的形参中
- 2. 封装一个bean直接来接收
- 3. 原生的HttpServletRequest接收
- 4. @PathVariable获取rest风格路径参数
- 5. @RequestParam绑定请求参数到方法形参
- 6. @RequestBody绑定请求参数到方法形参
- 7. @RequestHeader
- 8. @CookieValue
1. 直接把请求参数写在方法的形参中
@RequestMapping("/fun1")
public Book fun1(String name, Long id){
log.info("{} {}",id,name);
Book book=new Book(id, name);
return book;
}
![](http://e-1.cn/wp-content/uploads/2024/02/frc-a1bbb7ae41004252bb609475b0caf4ce.png)
2. 封装一个bean直接来接收
@RequestMapping("/fun2")
public Book fun2(Book book){
log.info("book={}",book);
return book;
}
![](http://e-1.cn/wp-content/uploads/2024/02/frc-52e276cde2aeaecc65a7d5a1b119424e.png)
3. 原生的HttpServletRequest接收
- 同时适用get、post方法
- 是整个请求,可以获取到所有的数据
- 可以和其他的注解配合适用
- HttpServletRequest、HttpServletResponse都是内置对象,可以使用
@RequestMapping("/fun3")
public Book fun3(HttpServletRequest request){
log.info("{} {}",request.getParameter("id"),request.getParameter("name"));
return new Book(Long.parseLong(request.getParameter("id")),request.getParameter("name"));
}
MapString, String[]> map = request.getParameterMap();
String pathInfo = request.getPathInfo();
ServletInputStream inputStream = request.getInputStream();
![](http://e-1.cn/wp-content/uploads/2024/02/frc-36fa4f1cc9e3e52da6c633e33c661cf7.png)
4. @PathVariable获取rest风格路径参数
@RequestMapping("/fun4/{id}/{name}")
public Book fun4(@PathVariable long id,@PathVariable String name){
log.info("{} {}",id,name);
Book book=new Book(id, name);
return book;
}
![](http://e-1.cn/wp-content/uploads/2024/02/frc-b80ee162452dc05bdfbd8d4ae513d455.png)
5. @RequestParam绑定请求参数到方法形参
@RequestMapping("/fun6")
public Book fun6(@RequestParam("name") String name,
@RequestParam("id") Long id){
log.info("{} {}",id,name);
Book book=new Book(id, name);
return book;
}
当请求参数username或者password不存在时会有异常发生,可以通过设置属性required=false解决
@RequestParam(value="username", required=false)
![](http://e-1.cn/wp-content/uploads/2024/02/frc-14b1f6a24c56912ea9e650351b1f512b.png)
6. @RequestBody绑定请求参数到方法形参
- 只能Post方法
- 参数必须Json字符串
- Body只能有一个
@RequestMapping("/fun7")
public Book fun7(@RequestBody Book book){
log.info("book={}",book);
return book;
}
![](http://e-1.cn/wp-content/uploads/2024/02/frc-ec88e0c6009156bb282addac3d810b4d.png)
7. @RequestHeader
- RequestHeader主要用来获取请求当中的请求头
@RequestMapping("/geteHeader")
public void getHeader(@RequestHeader("user-id") String userId){
}
@RequestMapping("/geteHeader")
public void getHeader(@RequestHeader MapString, String> headers){
}
@RequestMapping("/geteHeader")
public void getHeader(@RequestHeader HttpHeaders headers){
}
8. @CookieValue
- 使用@CookieValue注解来获得指定的 Cookie 的值。
@GetMapping("park/getCookie")
public String getCookieValue(@CookieValue("jid") String jId) {
System.out.println(jId);
return "success";
}