Discover how a simple annotation can save you hours of tedious routing code!
Why @GetMapping for GET requests in Spring Boot? - Purpose & Use Cases
Imagine you want to create a web app that shows user profiles when someone visits a URL like /users/123. You try to check the URL manually and send back the right data for each user.
Manually checking URLs and handling HTTP GET requests means writing lots of repetitive code. It's easy to make mistakes, forget to handle some URLs, or mix up request types. This slows you down and makes your app fragile.
The @GetMapping annotation in Spring Boot lets you easily link a method to a specific GET request URL. It automatically handles the routing, so your code stays clean and focused on what to do with the request.
if (request.getMethod().equals("GET") && request.getPath().equals("/users/123")) { // handle user 123 }
@GetMapping("/users/123") public User getUser123() { return userService.findUser(123); }
You can quickly build clear, maintainable web endpoints that respond to GET requests without messy manual checks.
When building a blog, you can use @GetMapping to show posts by URL like /posts/42 without writing complex routing logic yourself.
Manually handling GET requests is slow and error-prone.
@GetMapping simplifies routing for GET requests.
This leads to cleaner, easier-to-maintain web controllers.
Practice
@GetMapping annotation in a Spring Boot application?Solution
Step 1: Understand HTTP methods in Spring Boot
Spring Boot uses annotations to map HTTP methods like GET, POST, etc., to controller methods.Step 2: Identify the role of @GetMapping
@GetMapping specifically maps HTTP GET requests to the annotated method, so when a user visits a URL with a GET request, this method runs.Final Answer:
To map HTTP GET requests to specific controller methods -> Option BQuick Check:
@GetMapping = maps GET requests [OK]
- Confusing @GetMapping with @PostMapping
- Thinking @GetMapping handles POST or PUT requests
- Assuming it configures database or exceptions
/hello using @GetMapping in Spring Boot?Solution
Step 1: Check the correct use of @GetMapping syntax
@GetMapping requires the path to be a string, usually passed as path = "/url" or simply "/url".Step 2: Identify correct string usage and syntax
@GetMapping(path = "/hello") public String greet() { return "Hi"; } uses @GetMapping(path = "/hello") which is correct. @GetMapping(/hello) public String greet() { return "Hi"; } misses quotes around /hello. @GetMapping('/hello') public String greet() { return "Hi"; } uses single quotes, invalid for Java string literal. @GetMapping(path = hello) public String greet() { return "Hi"; } misses quotes around hello.Final Answer:
@GetMapping(path = "/hello") public String greet() { return "Hi"; } -> Option AQuick Check:
Correct syntax needs quotes and path attribute [OK]
- Omitting quotes around the path string
- Forgetting the leading slash in URL
- Using path without quotes causing syntax errors
/welcome?
@GetMapping("/welcome")
public String welcome() {
return "Welcome to Spring Boot!";
}Solution
Step 1: Understand the method mapping and return value
The method is mapped to GET requests at "/welcome" and returns a plain string.Step 2: Determine the response content
Since the method returns a string, Spring Boot will send "Welcome to Spring Boot!" as the response body for the GET request.Final Answer:
"Welcome to Spring Boot!" -> Option CQuick Check:
GET /welcome returns method's string [OK]
- Expecting a view name instead of response text
- Confusing 404 error when mapping exists
- Assuming empty or error response without cause
@GetMapping("/user/{id}")
public String getUser(@PathVariable int userId) {
return "User ID: " + userId;
}Solution
Step 1: Compare path variable name and method parameter
The path is defined as /user/{id} but the method parameter is named userId without specifying the variable name in @PathVariable.Step 2: Understand @PathVariable name matching
By default, the parameter name must match the path variable name or be explicitly specified like @PathVariable("id") int userId.Final Answer:
The @PathVariable parameter name does not match the path variable name -> Option AQuick Check:
Path variable names must match or be explicitly linked [OK]
- Not matching method parameter name with path variable
- Assuming type mismatch causes error here
- Thinking curly braces are invalid in @GetMapping path
/product/{category}/{id} and returns a string combining both path variables. Which of the following method signatures correctly uses @GetMapping and @PathVariable annotations?Solution
Step 1: Check @GetMapping path and method parameters
The path has two variables: {category} and {id}. The method must accept two parameters annotated with @PathVariable matching these names or explicitly linked.Step 2: Analyze each option's parameter annotations and types
@GetMapping("/product/{category}/{id}") public String getProduct(@PathVariable String cat, @PathVariable int id) { return cat + "-" + id; } uses parameter names that do not match path variables (cat != category), so fails without explicit names. @GetMapping("/product/{category}/{id}") public String getProduct(@PathVariable("category") String cat, @PathVariable("id") int id) { return cat + "-" + id; } explicitly links parameter names to path variables, which is safest. @GetMapping("/product/{category}/{id}") public String getProduct(@PathVariable int category, @PathVariable String id) { return category + "-" + id; } swaps types incorrectly. @GetMapping("/product/{category}/{id}") public String getProduct(String category, int id) { return category + "-" + id; } lacks @PathVariable annotations, so variables won't be bound.Step 3: Choose the best correct and safe option
@GetMapping("/product/{category}/{id}") public String getProduct(@PathVariable("category") String cat, @PathVariable("id") int id) { return cat + "-" + id; } explicitly names variables, avoiding errors if parameter names differ from path variables.Final Answer:
@GetMapping("/product/{category}/{id}") public String getProduct(@PathVariable("category") String cat, @PathVariable("id") int id) { return cat + "-" + id; } -> Option DQuick Check:
Explicit @PathVariable names ensure correct binding [OK]
- Omitting @PathVariable annotation
- Mismatching parameter types with path variables
- Not explicitly naming @PathVariable when names differ
Ready to prove it?
Pass the test and this pattern moves unknown
