REST controllers in Spring Boot are designed to receive HTTP requests, process them, and return HTTP responses, usually in JSON or XML format. They follow REST principles to make APIs easy to use and scalable.
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, World!"; } }
The method returns a plain String and the class is annotated with @RestController, so Spring Boot sends the string as the HTTP response body directly as plain text.
@RestController is a specialized version of @Controller that automatically adds @ResponseBody to all methods, so responses are serialized to JSON or XML by default.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetController { @GetMapping("/greet") public String greet() { return "Greetings!"; } }
If the controller class is not detected by Spring Boot (for example, it's outside the scan path or the app is not running), requests to its endpoints will return 404 errors.
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class UserController { @GetMapping("/user/{id}") public Map<String, Object> getUser(@PathVariable int id) { return Map.of("userId", id, "name", "User" + id); } }
The method returns a Map with keys 'userId' and 'name'. Spring Boot converts this Map to a JSON object with those keys and values. So the output is a JSON string with userId 42 and name 'User42'.