Why @GetMapping doesn't work in Thymeleaf?

·

1 min read

I recently came across this issue while working with thymeleaf in spring boot.
I defined an API like :

@RestController
@RequestMapping("/")
public class HomeController {
    @GetMapping("/home")
    public String getHomePage() {
        return "home";
    }
}

instead of :

@Controller
public class HomeController {
    @RequestMapping("/")
    public String getHomePage() {
        return "home";
    } 
}

You can see that the controller class annotated in both the cases are different like @RestController and @Controller respectively.
The question is while returning the html file in getHomePage() it renders properly in 2nd case and not in 1st case?
-> The crucial point to note here is in 1st case it is a RestController which means @RestController = @Controller + @ResponseBody in laymen terms. In this each method will return a Http response body which looks something like.

{
  "status": "success",
  "data": {
    "key" : "Values"
  },
  "message": "Data retrieved successfully"
}

The return type here is treated as Http response body which is typically converted into a JSON or other object to make it suitable for REST api.
Where as in 2nd case the @Controller allows you to specify logical view names which Thymeleaf can render. When you return "home" from a method in a @Controller, Spring's view resolver matches this logical name to a Thymeleaf template called home.html.