Thymeleaf bir web template enginesidir ve çoğunlukla web uygulamaları için HTML görünümlerini oluşturmada kullanılır.

https://thymeleaf.org

Thymeleaf templatesini oluşturmak için bazı Thymeleaf expressionlarını yapmamız gereklidir. Bazı thymeleaf expressions oluşturduğumuzda dynamic content oluşturulduğunda artık thymeleaf templatesini oluşturabiliriz.

  1. Web uygulamasında, Thymeleaf serverda işlenir ve sonuçlarda HTML şeklinde browsera döner.

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot içerisinde thymeleaf template dosyaları "src/main/resources/templates" altına gider ve web uygulamaları için .html extension ile başlarlar.



StudentController.java

@Controller
public class StudentController {
    @RequestMapping(path="/hello",method=RequestMethod.GET)
    public String helloStudent(Model theModel){
        return "hello";
    }
}


Thymeleafi html içerisinde belirtmek istersek xmlns olarak declare etmemiz gerekir:

<html xmlns:th="http://www.thymeleaf.org">

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Hello Student</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <span th:text="'Hello Student'"/>
    </body>
</html>


Eğer ki sadece text dönmek istersek

@ResponseBody annotationunu kullanmamız yeterlidir.

@Controller
public class TestController {
    @GetMapping("/test")
    @ResponseBody
    public String getTest(){
        return "Test Controller Geldi";
    }
}


Bir class'ın controller olduğunu belirtmek için

@Controller kullanılırken, o methodun sadece bir String katarı döneceğini belirtmek için ise @ResponseBody kullanılır ayrıca hangi URL'e endpointe istek geleceğini belirtmek için ise @GetMapping("/URL") belirtilir.

http://localhost:8080/test gidildiğinde


Thymeleaf ve CSS

Spring Boot bütün static resources için "src/main/resources/static" altındaki klasöre bakacaktır eğer ki biz her bir statiği istersek static klasörünün altındaki farklı klasörlere de bıraktırabiliriz.

  1. css/
  2. images/
  3. js/

gibi.

Eğer ki thymeleafta referans olarak göstermek istersek:

<link rel="stylesheet" href="@{/css/demo.css}"/>

şeklinde gösterebiliriz ve "@" sembolü uygulamanın context pathine referans gösterir.

Spring Boot default olarak static kaynaklara bakabilmek için aşağıdaki klasörlere girecektir.

src/main/resources

  1. /META-INF/resources
  2. /resources
  3. /static
  4. /public

Sırasıyla yukarıdan aşağı incelemeyi yapar.