The secret of Spring annotations: from URI to request body, everything is possible

The secret of Spring annotations: from URI to request body, everything is possible

Preface

Suppose you are an experienced software developer ready to explore the different annotations in the Spring framework to better handle various aspects of HTTP requests. Whether it's extracting variable values ​​from URIs, getting request headers, or handling file uploads, this blog will provide you with a comprehensive guide. We will delve into common annotations such as @PathVariable, @RequestBody, and @RequestParam, as well as other similar annotations such as @RequestHeader, @CookieValue, @ModelAttribute, and @RequestPart.

Whether you are a beginner or an experienced developer, this article will explain the role of each annotation in a simple and easy-to-understand way, provide clear code examples, and share practical application scenarios to help you better understand and Apply these powerful tools. There is no need to read complicated documents, just follow this article, and you will easily master the annotations about request parameters and request bodies in the Spring framework.

Are you ready? Let’s start this journey of Spring annotations full of fun and discovery!

Related notes

1. @PathVariable:

  • Purpose: Used to extract variable values ​​from URI.
  • Applicable scenarios: Usually used for RESTful style URLs, where part of the URI contains variable values.
  • Sample code:
    @GetMapping("/user/{userId}")
    public ResponseEntity<User> getUserById(@PathVariable Long userId) {
          
          
        // 根据userId获取用户信息
        User user = userService.getUserById(userId);
        return ResponseEntity.ok(user);
    }
    

2. @RequestBody:

  • Purpose: Used to obtain object data from the request body.
  • Applicable scenarios: Commonly used in POST and PUT requests. The client sends data such as JSON or XML as the request body.
  • Sample code:
    @PostMapping("/user")
    public ResponseEntity<Void> createUser(@RequestBody User newUser) {
          
          
        // 创建新用户
        userService.createUser(newUser);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    

3. @RequestParam:

  • Purpose: Used to obtain values ​​from request parameters.
  • Applicable scenarios: Commonly used to process query parameters, usually used in GET requests.
  • Sample code:
    @GetMapping("/users")
    public ResponseEntity<List<User>> getUsersByRole(@RequestParam("role") String role) {
          
          
        // 根据角色查询用户列表
        List<User> users = userService.getUsersByRole(role);
        return ResponseEntity.ok(users);
    }
    

In addition to @PathVariable, @RequestBody and @RequestParam, the Spring framework also provides some other related annotations for processing request parameters and request bodies. These annotations can be selected and used according to specific needs.

4. @RequestHeader:

  • Purpose: Used to obtain the value of HTTP request header information.
  • Sample code:
    @GetMapping("/user")
    public ResponseEntity<String> getUserAgent(@RequestHeader("User-Agent") String userAgent) {
          
          
        // 获取User-Agent请求头信息
        return ResponseEntity.ok("User-Agent: " + userAgent);
    }
    

5. @CookieValue:

  • Purpose: Used to obtain the cookie value in the HTTP request.
  • Sample code:
    @GetMapping("/user")
    public ResponseEntity<String> getCookieValue(@CookieValue("sessionId") String sessionId) {
          
          
        // 获取名为sessionId的Cookie值
        return ResponseEntity.ok("Session ID: " + sessionId);
    }
    

6. @ModelAttribute:

  • Purpose: Used to bind request parameters to model objects, usually used when submitting forms.
  • Sample code:
    @PostMapping("/user")
    public ResponseEntity<Void> createUser(@ModelAttribute User newUser) {
          
          
        // 创建新用户
        userService.createUser(newUser);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    

7. @RequestPart:

  • Purpose: Used to handle file uploads in requests.
  • Sample code:
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestPart("file") MultipartFile file) {
          
          
        // 处理上传的文件
        // ...
        return ResponseEntity.ok("File uploaded successfully");
    }
    

These annotations provide more options for processing request data. Appropriate annotations can be selected to process request parameters and request bodies according to different scenarios. Depending on your needs, you can combine these annotations to meet your application needs. Likewise, in order to improve the readability and maintainability of the code, it is recommended to add appropriate comments to the code.

Guess you like

Origin blog.csdn.net/Mrxiao_bo/article/details/133488135