GET Routes with @GetMapping
@GetMapping is an annotation that ties a method to an address. GET is the kind of request a browser sends when it visits an address.
Tie a method to /greet
This annotation ties the method to the address /greet.
@GetMapping("/greet")
public String greet() {Ask for the address
This command asks the app for the answer at /greet.
curl http://localhost:8080/greetExample
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetController {
@GetMapping("/greet")
public String greet() {
return "Hello, Spring Boot!";
}
}Key points
- @GetMapping is an annotation that ties a method to an address.
- The annotation sits above the method.
- The address goes inside the round brackets.
- GET is the kind of request a browser sends for a page.
- A browser visit to /greet asks the method for its answer.
- The method runs only when its address is asked for.
In this example, the annotation marks GreetController as a controller. The @GetMapping line ties the method to the address /greet. The method returns the text. A request to /greet gets the text Hello, Spring Boot!
Note
The address must start with a slash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @GetMapping do?