[SpringBoot series] Several ways to receive front-end parameters

In Spring Boot, there are several ways to receive front-end parameters:

  1. @RequestParam This is the most basic one, which is mapped to the parameters of the method through the request parameter name, such as:
@GetMapping("/test")
public String test(@RequestParam("name") String username) {
    // ...
}

Then the request URL is /test?name=xxx.

  1. @RequestHeader This method receives request header information as a parameter, such as:
@GetMapping("/test") 
public String test(@RequestHeader("User-Agent") String userAgent) {
    // ...
}
  1. @CookieValue This method receives cookies as parameters, such as:
@GetMapping("/test")
public String test(@CookieValue("JSESSIONID") String sessionId) {
    // ... 
}
  1. @PathVariable This method receives URL path parameters as parameters, such as:
@GetMapping("/test/{id}")
public String test(@PathVariable("id") int id) {
    // ...
}

Then the request URL is /test/10.

  1. @RequestBody This method receives the request body sent by the front end and maps it to an object, which is often used for POST requests, such as:
@PostMapping("/test")
public String test(@RequestBody User user) {
    // ...
}

Then the request body sent by the front end may be in JSON format, which will be mapped to the User object.

  1. HttpServletRequest This is the most primitive way to obtain arbitrary request information through the HttpServletRequest object, such as:
@GetMapping("/test")
public String test(HttpServletRequest request) {
    String name = request.getParameter("name");
    String header = request.getHeader("User-Agent");
    // ...
}

The above are several commonly used methods of receiving front-end parameters in Spring Boot, which can be selected according to needs.

おすすめ

転載: blog.csdn.net/jinxinxin1314/article/details/130415985