In Spring Boot, there are several ways to receive front-end parameters:
- @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.
- @RequestHeader This method receives request header information as a parameter, such as:
@GetMapping("/test")
public String test(@RequestHeader("User-Agent") String userAgent) {
// ...
}
- @CookieValue This method receives cookies as parameters, such as:
@GetMapping("/test")
public String test(@CookieValue("JSESSIONID") String sessionId) {
// ...
}
- @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.
- @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.
- 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.