@GetMapping helps your Spring Boot app listen for GET requests from users or other apps. It makes your app respond with data or pages when someone asks for them.
@GetMapping for GET requests in Spring Boot
@GetMapping("/path")
public ReturnType methodName() {
// code to handle GET request
}The string inside @GetMapping is the URL path this method listens to.
The method should return data or a view to show to the user.
@GetMapping("/hello") public String sayHello() { return "Hello World!"; }
@GetMapping("/users") public List<User> getUsers() { return userService.findAllUsers(); }
@GetMapping("/product/{id}") public Product getProduct(@PathVariable int id) { return productService.findById(id); }
This Spring Boot controller has two GET endpoints. One returns a simple greeting. The other returns a personalized greeting using a name from the URL.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @GetMapping("/greet") public String greet() { return "Hello from Spring Boot!"; } @GetMapping("/greet/{name}") public String greetName(@PathVariable String name) { return "Hello, " + name + "!"; } }
Always use @RestController or @Controller to tell Spring this class handles web requests.
Use @PathVariable to get parts of the URL as method parameters.
GET requests should not change data on the server; they only fetch data.
@GetMapping maps HTTP GET requests to methods in your Spring Boot app.
It helps your app respond with data or pages when users visit URLs.
Use path variables to get dynamic parts of the URL.
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
