Spring Boot Basic Controller
@RestController
@RequestMapping("/api")
1. @RestController:
Usage:
It is typically used in classes where you are defining API endpoints that return data (like JSON objects), which is common in REST APIs
//Code
@RestController
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
2. @RequestMapping("/api")
Usage:
- At the class level,
@RequestMapping("/api") could mean that all the API endpoints in this controller will start with /api. - You can define additional sub-paths or HTTP methods at the method level.
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/users")
public List<String> getAllUsers() {
return List.of("John", "Jane", "Doe");
}
@PostMapping("/users")
public String addUser(@RequestBody String user) {
return "User " + user + " added.";
}
}
Comments
Post a Comment