Technology Sharing

SpringBoot common annotations

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

@RestController

It is the coupling of @ResponseBody and @Controller.

@Controller indicates that the class is a controller, and @ResponseBody indicates that the object returned by the controller's method is used directly as the body of the HTTP response, rather than as a view.

Comments written in parameter lists

@PathVariable

@GetMapping("/users/{userId}")

  • Used to extract variables from URL templates.
  • When you define a RESTful API, you can use this to capture path parameters defined in the URL.
  • For example, if you have a URL pattern/users/{userId}, and the requested URL is/users/123,So123can be used asuserIdParameters are passed to the controller method.
  • Usually with@RequestMappingor@GetMapping@PostMappingUsed together with other annotations.
  1. @GetMapping("/users/{userId}")
  2. public User getUserById(@PathVariable("userId") int userId) { // 根据userId获取用户信息 }

@RequestParam

  • Used to extract values ​​from the request's query parameters.
  • It allows you to access the query string portion of the URL, such as?name=value
  • Even if no parameters are specified in the request, you can userequired=falseAttributes are set to be optional, or bydefaultValueThe property provides a default value.
  • Usually with@RequestMappingor@GetMapping@PostMappingUsed together with other annotations.
  1. @GetMapping("/search")
  2. public List<User> searchUsers(@RequestParam(value = "name", required = false) String name) { // 根据提供的name参数搜索用户 }

@RequestBody

  • @RequestBodyAllows you to automatically convert (through appropriate converters such as Jackson or JAXB) the request body (JSON, XML, etc.) sent by the client and bind it to an object.
  • When using@RequestBodyWhen calling HttpChannel("application/json", "application/json"); , the request sent by the client is expected to have a non-empty request body. If the request body is empty, Spring will throw an exception.
  • Used to map the body of an HTTP request to the parameters of a controller method.
  • Mainly used for requests such as POST, PUT, and PATCH, which usually require the client to submit data to create or update resources
  1. @PostMapping("/users")
  2. public ResponseEntity<?> addUser(@RequestBody User user) {
  3. // 将接收到的User对象保存到数据库
  4. userService.addUser(user);
  5. return ResponseEntity.ok().build();
  6. }