Junior — Middle
How can a controller be implemented within the Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, a controller is implemented as a class annotated with @Controller or @RestController (for REST APIs). The controller handles HTTP requests by mapping URLs to class methods.
Example of a simple REST controller:
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, Spring!";
}
}
Here:
@RestControllercombines@Controllerand@ResponseBody, returning data directly.@GetMappingmaps an HTTP GET request to the path/helloto thesayHellomethod.
For more complex controllers, you can use request parameters, paths, request bodies, and return objects that Spring automatically serializes into JSON.