STACKJAVA

Code ví dụ Spring MVC Thymeleaf Hello – dùng annotation config

Code ví dụ Spring MVC Thymeleaf Hello – dùng annotation config

Code ví dụ Spring MVC Thymeleaf Hello – dùng xml config

Hướng dẫn chi tiết cấu hình project Spring MVC + Thymeleaf sử dụng annotation config, giải thích các bean, các thuộc tính trong bean config.

(Xem lại Ví dụ Spring MVC Hello sử dụng annotation config)

(Xem lại Giới thiệu Thymeleaf)

Ở ví dụ này mình dùng:

Tạo maven Project

Thư viện sử dụng:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>SpringThymeleaf</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
  </properties>
  <dependencies>
    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- Thymeleaf -->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf</artifactId>
      <version>${thymeleaf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>${thymeleaf.version}</version>
    </dependency>
  </dependencies>
</project>

File web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <display-name>SpringThymeleaf</display-name>
</web-app>

File Spring config:

package stackjava.com.springthymeleaf.webconfig;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[] { SpringWebConfig.class };
  }

  @Override
  protected String[] getServletMappings() {
    return new String[] { "/" };
  }

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return null;
  }
}
package stackjava.com.springthymeleaf.webconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

@EnableWebMvc // mvc:annotation-driven
@Configuration
@ComponentScan({ "stackjava.com.springthymeleaf" })
public class SpringWebConfig implements WebMvcConfigurer {

  @Autowired
  private ApplicationContext applicationContext;

  @Bean
  public SpringResourceTemplateResolver templateResolver() {
    // SpringResourceTemplateResolver automatically integrates with Spring's own
    // resource resolution infrastructure, which is highly recommended.
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("/WEB-INF/templates/");
    templateResolver.setSuffix(".html");
    // HTML is the default value, added here for the sake of clarity.
    templateResolver.setTemplateMode(TemplateMode.HTML);
    // Template cache is true by default. Set to false if you want
    // templates to be automatically updated when modified.
    templateResolver.setCacheable(true);
    return templateResolver;

  }

  @Bean
  public SpringTemplateEngine templateEngine() {
    // SpringTemplateEngine automatically applies SpringStandardDialect and
    // enables Spring's own MessageSource message resolution mechanisms.
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
    // speed up execution in most scenarios, but might be incompatible
    // with specific cases when expressions in one template are reused
    // across different data types, so this flag is "false" by default
    // for safer backwards compatibility.
    templateEngine.setEnableSpringELCompiler(true);
    return templateEngine;
  }
  
   @Bean
    public ViewResolver viewResolver(){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }
}

File controller:

package stackjava.com.springthymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

  @RequestMapping("/")
  public String index(final Model model) {
    model.addAttribute("message", "hello");
    return "index";
  }

}

File view:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring MVC + Thymeleaf</title>
</head>
<body>
  <h1>Hello: Spring MVC + Thymeleaf</h1>
    <p th:text="'message: ' + ${message} + '!'" />
</body>
</html>

 

Lưu ý: nhớ khai báo name space: xmlns:th="http://www.thymeleaf.org" trong thẻ html để trình ide hiểu được các thẻ th.

Thẻ th:text="'message: ' + ${message} + '!'"  được coi như 1 thẻ html

Nếu bạn mở trực tiếp file index.html thì thẻ th sẽ không có ý nghĩa và sẽ bị bỏ qua (vì thẻ th không có trong ngôn ngữ html)

Nếu bạn chạy file index.html trên server thì template engine sẽ convert thẻ th sang thẻ html và các giá trị tương ứng

Code ví dụ Spring MVC Thymeleaf Hello – dùng XML config

Demo

Trường hợp mở file index.html trực tiếp trên trình duyệt

Trường hợp chạy server, thẻ th và giá trị message được generate ra giá trị tương ứng.

Code ví dụ Spring MVC Thymeleaf Hello – dùng annotation config

Okay, Done!

Download code ví dụ trên tại đây

References:

http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/thymeleaf-views/