0
0
SpringbootConceptBeginner · 3 min read

@GetMapping in Spring: What It Is and How It Works

@GetMapping is a Spring annotation used to map HTTP GET requests to specific handler methods in a controller. It simplifies defining routes that respond to GET requests by replacing older, more verbose annotations.
⚙️

How It Works

@GetMapping works by linking a URL path to a method in a Spring controller that should run when a user visits that URL with a GET request. Think of it like a receptionist who listens for a specific question (the URL) and then directs you to the right person (the method) to answer it.

When a web browser or client sends a GET request to the server, Spring looks for a method annotated with @GetMapping that matches the requested path. It then runs that method and sends back the result, usually a web page or data.

This annotation is a shortcut for @RequestMapping(method = RequestMethod.GET), making the code cleaner and easier to read.

💻

Example

This example shows a simple Spring controller with a method that responds to GET requests at the path /hello. When you visit http://localhost:8080/hello, it returns a greeting message.

java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, welcome to Spring!";
    }
}
Output
Hello, welcome to Spring!
🎯

When to Use

Use @GetMapping when you want to handle HTTP GET requests in your Spring web application. GET requests are typically used to retrieve data or display pages without changing anything on the server.

For example, use it to show a list of products, display a user profile page, or fetch information from a database to show on a website.

It is best for safe operations where the user only wants to read or view data, not modify it.

Key Points

  • @GetMapping maps HTTP GET requests to controller methods.
  • It is a shortcut for @RequestMapping(method = RequestMethod.GET).
  • Used for retrieving or displaying data without side effects.
  • Improves code readability and simplicity.
  • Commonly used in REST APIs and web applications.

Key Takeaways

@GetMapping handles HTTP GET requests in Spring controllers.
It simplifies routing by replacing more verbose annotations.
Use it to serve pages or data without changing server state.
It improves code clarity and is common in RESTful services.