0
0
Spring Bootframework~5 mins

@GetMapping for GET requests in Spring Boot

Choose your learning style9 modes available
Introduction

@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.

When you want to show a webpage or data when someone visits a URL.
When you want to get information from your app without changing anything.
When building APIs that send data back to users or other apps.
When you want to handle simple requests like showing a list or details.
When you want to map a URL path to a method that returns data.
Syntax
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.

Examples
This method listens to GET requests at /hello and returns a simple text.
Spring Boot
@GetMapping("/hello")
public String sayHello() {
    return "Hello World!";
}
This method returns a list of users when someone visits /users.
Spring Boot
@GetMapping("/users")
public List<User> getUsers() {
    return userService.findAllUsers();
}
This method uses a path variable to get a product by its id from the URL.
Spring Boot
@GetMapping("/product/{id}")
public Product getProduct(@PathVariable int id) {
    return productService.findById(id);
}
Sample Program

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.

Spring Boot
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 + "!";
    }
}
OutputSuccess
Important Notes

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.

Summary

@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.