Search code examples
springthymeleaf

Thymleaf not returning templates but strings


I'm building an application with thymeleaf, and i've encountered this problem where when returning a template as for example ...return "products";... and when I visit the url i addressed in @GetMapping() i get the string "products" instead of rendered template

enter image description here.

enter image description here

@Service
public class HomeService {

    @Autowired
    ProductRepository productRepository;

    public String getProducts(Model model) {
        List<Product> products= productRepository.findAll();

        if (!products.isEmpty()){
            model.addAttribute("product", products);
            return "products";
        }else{
            return "404";
        }
    }
}

@RestController
public class HomeController {

    @Autowired
    HomeService homeService;

    @GetMapping("/home")
    public String home(Model model){
        return homeService.getProducts(model);
    }
}

Solution

  • As stated above, the @RestController annotation should be replaced with the @Controller annotation.

    The @RestController annotation in Spring is designed for building REST web services that return data in JSON or XML format, and it does not support the use of view templating engines like Thymeleaf. If you want to render HTML views, you should use the @Controller. In @Controller, we can return a view in Spring Web MVC.