17 Kasım 2020 Salı

SpringMVC Thymeleaf Kullanımı

Giriş
Thymeleaf server side template kullanılır. JSP'nin biraz daha gelişmiş hali diyebiliriz. Açıklaması şöyle
Thymeleaf is a Java template engine for processing XML, HTML and HTML5 documents. Thymeleaf is a popular server-side template engine for both web and standalone Java applications. The biggest advantage of using Thymeleaf is that it brings natural templates to your development workflow.

Spring-boot provides excellent support for the Thymeleaf template engine, making the whole integration process very simple and straightforward.

Maven
Şu satırı dahil ederiz
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
</dependencies>
Kullanım
1. Template dosyaları dizinlere yerleştirilir
2. SpringTemplateEngine ile rendering işlemi yapılır. Rendering sonrasında elimizde bir String vardır. Bunu bir REST noktasından dönebiliriz.
3. Spring MVC kullanıyorsak direkt render edilecek dosyanın ismini döndürürüz. Render işlemi için gereken değişkenler model.addAttribute() çağrısı ile model'e geçilir.
Örnek
Şöyle yaparız. html dosyasında xmlns belirtiliyor.
@Controller
public class IndexController {

  @GetMapping("/")
  public String index(Model model) {
    // add `message` attribute
    model.addAttribute(“message”, “Thank you for visiting.”);

    // return view name
    return "index";
  }
}

<!DOCTYPE html> 
<html lang=”en” xmlns:th=”http://www.thymeleaf.org">
  <head>
    <meta charset=”UTF-8">
    <title>Spring Boot Thymeleaf Web Application</title>
  </head>
  <body>
    <h1>Welcome to Spring Boot Thymeleaf</h1>
    <p> Hey there!
      <th:block th:text=”${message}”>message</th:block>
    </p>
  </body>
</html>

Dizinler
1. Static Dizini
Template dosyalar tarafından kullanılan static dosyalar şu dizindedir
src/main/resources/static/
Bu dizinde consumer.html dosyası varsa erişmek için "localhost:8001/consumer" adresine gideriz. 
Örnek
Eğer consumer.html bir js dosyası kullanıyorsa html dosyasında şöyle yaparız
<script src="js/active-consumer.js"></script>
Daha sonra "src/main/resources/static/js/active-consumer.js" dosyasını yaratmak gerekir.

2. Template Dizini
Tüm template dosyaları şu dizindedir.
src/main/resources/templates
Tüm html dosyaları xmlns:th satırını içermelidir. Şöyle olmalıdır
<!DOCTYPE html>
<html xmlns:th=”http://www.thymeleaf.org">

<head>
  <meta charset=”UTF-8">
  <title>...</title>
</head>

<body>
  <h1 th:text=”${name}”></h1>
</body>
</html>
Örnek
Elimizde şöyle bir kod olsun
@Controller
public class HomeController {

  private static final String appName = "ThymeleafTour";

  @GetMapping("/")
  public String home(Model model,
     RequestParam(value = "name", required = false, defaultValue = "Guest") String name) {

    model.addAttribute("name", name);
    model.addAttribute("title", appName);
    return "home";
  }
}
"src/main/resources/templates/home.html" dosyası şöyledir. <link> ile erişilmeye çalışılan static css "src/main/resources/templates/css/main.csss" dosyasıdır
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title th:text="${title}"></title>
    <link rel="stylesheet" href="/css/main.css" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <div class="page-content">
      <h1 th:text="|Hello ${name}!|"></h1>
      <h2 th:text="|Welcome to ${title} application|"></h2>
    </div>
  </body>
</html>
Double Brace
Belirtilen nesneyi kendi tipine göre bir formatter'a gönderir ve bunun sonucunu kullanır.

Örnek
Şöyle yaparız. Burada sendDate alanı bir LocalDate olsun
<td th:text="${{submission.sentDate}}"></td>
Formatter şöyle olsun
import org.springframework.format.Formatter;

public class DateFormatter implements Formatter<LocalDate> {
  
  @Override
  public String print(LocalDate object, Locale locale) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    return object.format(formatter);
  }
  @Override
  public LocalDate parse(String object, Locale locale) throws  ParseException {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    return LocalDate.parse(object, formatter);
  }
}
Formatter'ı Spring'e tanıtırız. Şöyle yaparız
@Configuration
@EnableWebMvc
public class ConfigClass extends WebMvcConfigurerAdapter {
  public void addFormatters(FormatterRegistry formatterRegistry) {
    formatterRegistry.addFormatter(dateFormatter());
  }
  @Bean
  public DateFormatter dateFormatter() {
    return new DateFormatter();
  }
}

Single Brace
sec:authorize
SpringSecurity ile birlikte çalışır ve doğrulanmış kişilerin sayfaya erişimine izin verir. Bir örnek burada

th:action
Şöyle yaparız
<form th:action="@{/loginProcess}" th:method="post" >

  <label for="email">E-Mail Adresse:</label>
  <input type="email" ...>

  <label for="password">Password:</label>
  <input type="password" ...>
  
  <input type="checkbox"> Remember me </label>
  <button type="submit" ...>Submit</button>
</form>

th:text
Modeldeki değerlere template içinde th:text="${attributeName}" şeklinde erişilir.
Örnek
Şöyle yaparız
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title th:remove="all">Registration confirmation</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <style type="text/css">
    body {
      font-family: calibri, 'DejaVu Sans', Arial, Helvetica, sans-serif;
    }
    a.link {
      border: solid 1px #000;
      background-color: #000;
      text-decoration: none;
      color: #fff;
      font-weight: bold;
      display: block;
      width: 360px;
      text-align: center;
      padding: 10px 0;
    }
  </style>
</head>
<body>
<h1>Confirm your account</h1>
<div>Welcome to AwesomeApp <b th:text="${name}">name</b> !</div>
<p>
  Your account has been created on our platform; here is your login information
  <br/><br/>
  Email address : <b th:text="${email}">email</b><br/>
  <br/>
  To confirm the validity of your email address, please click on the link below
</p>
<p style="text-align: left;">
  <a class="link" href="#" th:href="${url}">Confirm my account</a>
</p>
<br>
<p>
  <img src="images/spring.png" data-th-src="|cid:springLogo|" height="80" />
</p>
<p>
  Regards, <br />
  &emsp; <em>The AwesomeApp Team</em>
</p>
</body>
</html>

Kullanmak için şöyle yaparız
Context ctx = new Context(LocaleContextHolder.getLocale());
ctx.setVariable("email", user.getEmail());
ctx.setVariable("name", user.getName());
ctx.setVariable("springLogo", "templates/images/spring.png");
ctx.setVariable("url", confirmationUrl);
    
String htmlContent = this.htmlTemplateEngine.process("registration", ctx);

th:each
Liste üzerinde dolaşmayı sağlar

Örnek
Controller sınıfında şöyle bir kod olsun
public class Student implements Serializable {
  private Integer id;
  private String name;
  // standard getters and setters
}

List<Student> students = new ArrayList<>();
// logic to build student data
model.addAttribute("students", students);
Şöyle yaparız
<tbody>
  <tr th:each="student: ${students}">
  <td th:text="${student.id}" />
   <td th:text="${student.name}" />
  </tr>
</tbody>
Örnek
Bir hasta listesinin  yanında iki tane düğme çıkartmak için şöyle yaparız
<tr th:each="patient : ${patients}">
  <td th:text="${patient.name}">Patient name</td>
  <td th:text="${patient.surname}">Patient surname</td>
  <td th:text="${patient.age}">Patient age</td>
  <td th:text="${patient.covidInfo}">Patient covid information</td>
  <td>
    <form action="#" th:action="@{'/updateCovidInfo/'+${patient.id}}" th:method="post" >
      <input type="hidden" name="_method" value="post" />
      <button type="submit" id="Approve" name="Approve">Update Covid Info </button>
    </form>
  </td>

  <td>
    <form action="#" th:action="@{'/deletePatient/'+${patient.id}}" th:method="post" >
      <button type="submit" >Delete Patient </button>
    </form>
  </td>
</tr>
th:if ve th:unless
if/else gibidir

th:href
Örnek
Şöyle yaparız
<p style="text-align: left;">
  <a class="link" href="#" th:href="${url}">Confirm my account</a>
</p>

th:switch ve th:case
Örnek ver

th:replace
Örnek ver

th:insert
Örnek ver



Hiç yorum yok:

Yorum Gönder