Search code examples
spring-bootthymeleaf

Thymeleaf doesn't work in spring boot and also doesn't show in console


after trying multiple times on freemarker to work, I switched to thymeleaf and also faced the same problem. When returning the html file, it's just a string value and not the html file in the templates folder.

I don't know why it doesn't even start in console, when I watched youtube thymeleaf videos it shows in their console.

package com.example.demo;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class controller {

    @GetMapping
    public String getUser(Model model) {
        model.addAttribute("something", "welcome to the club");
        return "user";
    }
}


here is the html file in main/resources/templates

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Code</title>
</head>
<body>
<h1 th:text="${something}"></h1>
</body>
</html>

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
</project>


Solution

  • Solved now, I replace @RestController with @Controller because @RestController adds @ResponseBody and prevents to get the view.