Controllers help define API endpoints that an application exposes. You can use one of the below ways to define controllers in SpringBoot.


@Controller

package starter.main.content
 
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
 
@Controller
class StarterController {
 
    @GetMapping("/")
    fun sayHello(): String {
        return "hello.html"
    }
}

Warning hello.html should be located within Resources/static

Should return a ModelAndView object or a String view name


@RestController

package starter.main.content
 
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
 
@RestController
class StarterController {
 
    @GetMapping("/")
    fun sayHello(): String {
        return "Hello"
    }
}

@Controller (RESTful)

package starter.main.content
 
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
 
@Controller
class StarterController {
 
    @GetMapping("/")
    @ResponseBody
    fun sayHello(): String {
        return "Hello"
    }
}

@ResponseBody is mandatory for @Controller in a REST api endpoint as we typically return data directly