【SpringBoot系列】接收前端参数的几种方式

在Spring Boot中,有以下几种方式接收前端参数:

  1. @RequestParam这是最基本的一种,通过请求参数名映射到方法的参数上,如:
@GetMapping("/test")
public String test(@RequestParam("name") String username) {
    // ...
}

然后请求URL为/test?name=xxx。

  1. @RequestHeader这种方式接收请求头信息作为参数,如:
@GetMapping("/test") 
public String test(@RequestHeader("User-Agent") String userAgent) {
    // ...
}
  1. @CookieValue这种方式接收cookie作为参数,如:
@GetMapping("/test")
public String test(@CookieValue("JSESSIONID") String sessionId) {
    // ... 
}
  1. @PathVariable这种方式接收URL路径参数作为参数,如:
@GetMapping("/test/{id}")
public String test(@PathVariable("id") int id) {
    // ...
}

然后请求URL为/test/10。

  1. @RequestBody这种方式接收前端发送过来的请求体,并将其映射到一个对象上,常用于POST请求,如:
@PostMapping("/test")
public String test(@RequestBody User user) {
    // ...
}

然后前端发送的请求体可能是JSON格式,会映射到User对象上。

  1. HttpServletRequest这是最原始的方式,通过HttpServletRequest对象获取任意请求信息,如:
@GetMapping("/test")
public String test(HttpServletRequest request) {
    String name = request.getParameter("name");
    String header = request.getHeader("User-Agent");
    // ...
}

以上就是Spring Boot中常用的几种接收前端参数的方式,可以根据需要选择使用。

猜你喜欢

转载自blog.csdn.net/jinxinxin1314/article/details/130415985