Sobes.tech
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:

  • @RestController combines @Controller and @ResponseBody, returning data directly.
  • @GetMapping maps an HTTP GET request to the path /hello to the sayHello method.

For more complex controllers, you can use request parameters, paths, request bodies, and return objects that Spring automatically serializes into JSON.