SoFunction
Updated on 2025-03-08

Summary of the API interface parameter acquisition method in SpringBoot

introduction

In Spring Boot, API interface parameters can be obtained in many ways, depending on the API interface parameter type you define (such as path parameters, query parameters, request body parameters, request headers, etc.). The following are some common parameters and corresponding Java sample code:

1.Path Variable

use@PathVariableAnnotation gets parameters from the URL path.

    @RestController
    @RequestMapping("/users")
    public class UserController {
 
        @GetMapping("/{id}")
        public ResponseEntity<String> getUserById(@PathVariable Long id) {
            // Processing logic            return ("User with ID: " + id);
        }
    }

2. Query Parameter

use@RequestParamAnnotation gets parameters from the URL query string.

    @RestController
    @RequestMapping("/users")
    public class UserController {
 
        @GetMapping("/search")
        public ResponseEntity<String> searchUsers(@RequestParam String name) {
            // Processing logic            return ("Searching for user with name: " + name);
        }
 
        // You can also set the default value        @GetMapping("/searchWithDefault")
        public ResponseEntity<String> searchUsersWithDefault(@RequestParam(defaultValue = "John") String name) {
            // Processing logic            return ("Searching for user with name: " + name);
        }
    }

3. Request Body parameter

use@RequestBodyAnnotation gets parameters from the HTTP request body, usually used for POST or PUT requests.

    @RestController
    @RequestMapping("/users")
    public class UserController {
 
        @PostMapping("/")
        public ResponseEntity<String> createUser(@RequestBody User user) {
            // Processing logic            return ("User created with name: " + ());
        }
 
        // Assume that the User class is as follows        static class User {
            private String name;
            // getters and setters
        }
    }

4. Request header parameters (Request Header)

Usually, the annotation is not used directly to obtain the request header parameters, but it can be done throughHttpServletRequestObject or@RequestHeaderAnnotations are obtained.

use@RequestHeaderannotation:

    @RestController
    @RequestMapping("/users")
    public class UserController {
 
        @GetMapping("/")
        public ResponseEntity<String> getUsers(@RequestHeader("Authorization") String authToken) {
            // Processing logic            return ("Authorization token: " + authToken);
        }
    }

useHttpServletRequestObject:

    @RestController
    @RequestMapping("/users")
    public class UserController {
 
        @GetMapping("/")
        public ResponseEntity<String> getUsers(HttpServletRequest request) {
            String authToken = ("Authorization");
            // Processing logic            return ("Authorization token from HttpServletRequest: " + authToken);
        }
    }

5.@CookieValue

Cookies are needed when we need to maintain stateful interaction with the client. At this time, when the server reads the cookie data, it can be used as follows@CookieValueTo read the cookieSessionIddata.

@GetMapping("/user")
@ResponseBody()
public List<User> getUserList(@CookieValue(name = "SessionId") String sessionId) {
     return ();
}

6.@MatrixVariable

We don't use a lot of this, but some foreign systems provide this type of API parameters, and the parameters of this API are passed and divided.

For example: this request /books/reviews;isbn=1234;topN=5; can use @MatrixVariable to load the parameters used in the URL as shown below.

@GetMapping("/books/reviews")
@ResponseBody()
public List<BookReview> getBookReviews( 
  @MatrixVariable String isbn,  @MatrixVariable Integer topN) {
  return (isbn, topN);
}

7. Form Data

For form data in POST requests, you can usually use @ModelAttribute or @RequestParam to get it. However, if the form data is sent as a request body (Content-Type: application/x-www-form-urlencoded), you can use @RequestParam directly. If the form data is in JSON format, you should use @RequestBody.

Other parts of the API

You can also use other parts of the Servlet API such as HttpServletResponse, HttpSession, etc. to handle requests and responses. But in Spring Boot, it is generally recommended to use the advanced abstraction provided by Spring MVC to simplify development.

Note: In order to correctly parse JSON data in the request body, you need to add an appropriate JSON library (such as Jackson) to your Spring Boot project and make sure that the requested Content-Type is set to application/json.

The above is the detailed content of the method of obtaining API interface parameters in SpringBoot. For more information about SpringBoot API interface parameters, please pay attention to my other related articles!