6 Essential Ways to Read Request Parameters in Spring Boot
This article explains six common techniques—@RequestParam, @PathVariable, @MatrixVariable, @RequestBody, @RequestHeader, and @CookieValue—for extracting request data in Spring Boot APIs, complete with concise code examples and usage guidance.
When developing APIs with Spring Boot, reading request parameters is a fundamental operation, and Spring Boot provides multiple mechanisms to satisfy different design requirements. This article summarizes six common ways to read request parameters.
@RequestParam
The most frequently used annotation for loading query parameters that appear after the “?” in a URL.
@GetMapping("/user")
@ResponseBody
public User findUserByName(@RequestParam("name") String name) {
return userRepo.findByName(name);
}@PathVariable
Commonly used in RESTful APIs to load parameters embedded in the URL path.
@GetMapping("/user/{id}")
@ResponseBody
public User findUserById(@PathVariable("id") String id) {
return userRepo.findById(id);
}@MatrixVariable
Less common, used by some systems to handle parameters separated by semicolons in the URL.
@GetMapping("/books/reviews")
@ResponseBody
public List<BookReview> getBookReviews(@MatrixVariable String isbn, @MatrixVariable Integer topN) {
return bookReviewsLogic.getTopNReviewsByIsbn(isbn, topN);
}@RequestBody
Used to load complex request bodies (payloads) for POST or PUT requests.
@PostMapping("/add")
public boolean addAccounts(@RequestBody List<Account> accounts) throws SQLException {
accounts.stream().forEach(a -> {
a.setCreatedOn(Timestamp.from(Instant.now()));
a.setLastLogin(Timestamp.from(Instant.now()));
});
return notificationLogic.addAccounts(accounts);
}@RequestHeader
Loads data from HTTP request headers, useful for passing metadata such as distributed tracing IDs.
@GetMapping("/user")
@ResponseBody
public List<User> getUserList(@RequestHeader("Authorization") String authToken) {
return userRepo.findAll();
}@CookieValue
Retrieves values from cookies, enabling stateful interactions with the client.
@GetMapping("/user")
@ResponseBody
public List<User> getUserList(@CookieValue(name = "SessionId") String sessionId) {
return userRepo.findAll();
}That concludes the overview of these request‑parameter extraction techniques in Spring Boot.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
