6 Essential Ways to Read Request Parameters in Spring Boot
This guide explains six common Spring Boot techniques—@RequestParam, @PathVariable, @MatrixVariable, @RequestBody, @RequestHeader, and @CookieValue—for extracting URL query strings, path variables, matrix variables, request bodies, headers, and cookies, complete with code examples for each method.
When developing APIs with Spring Boot, reading request parameters is a fundamental operation. Spring Boot provides multiple mechanisms to satisfy different API design requirements. This article summarizes six common ways to read request parameters.
@RequestParam
This is the most frequently used annotation for loading parameters that appear after the ? in a URL query string.
@GetMapping("/user")
@ResponseBody()
public User findUserByName(@RequestParam("name") String name) {
return userRepo.findByName(name);
}@PathVariable
Common in RESTful APIs, this annotation loads parameters embedded in the URL path.
@GetMapping("/user/{id}")
@ResponseBody()
public User findUserById(@PathVariable("id") String id) {
return userRepo.findById(id);
}@MatrixVariable
Less common, this handles parameters separated by semicolons in the URL, as some foreign systems provide.
@GetMapping("/books/reviews")
@ResponseBody()
public List<BookReview> getBookReviews(@MatrixVariable String isbn, @MatrixVariable Integer topN) {
return bookReviewsLogic.getTopNReviewsByIsbn(isbn, topN);
}@RequestBody
Used for loading complex request bodies (payload) in POST/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
This annotation loads data from request headers, useful for infrastructure concerns such as passing a TraceID.
@GetMapping("/user")
@ResponseBody()
public List<User> getUserList(@RequestHeader("Authorization") String authToken) {
return userRepo.findAll();
}@CookieValue
When stateful interaction with the client is needed, this annotation reads cookie values, such as a SessionId.
@GetMapping("/user")
@ResponseBody()
public List<User> getUserList(@CookieValue(name = "SessionId") String sessionId) {
return userRepo.findAll();
}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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
