天天看點

spring-boot學習:十五、spring-boot內建thymeleaf

springboot2.x和spring5.x不再支援velocity,推薦使用thymeleaf,原因是velocity更新太慢或太少,社群不夠活躍。

實作步驟:

1.引入jar包

<dependency><!--Web相關依賴-->
   <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>
           

2.在application.properties中配置thymeleaf

# thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.suffix=.htm
           

注意:

1) 網上很多文章說需要配置spring.thymeleaf.mode=LEGACYHTML5,在新版springboot中LEGACYHTML5已經廢棄,使用HTML

2) spring.thymeleaf.prefix=必須配正确,特别是斜杠,否則可能報錯template might not exist or might not be accessible by any of the configured

3.編寫頁面Controller

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

@Controller
public class TestController {
	@RequestMapping("/index.do")
	public String index(Model model) {
		model.addAttribute("welcome", "Hello Kevin");
		return "index";
	}
}
           

4.編寫頁面index.htm

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

備注:

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

命名空間标記目前頁面屬于thyemeleaf模闆

  1. 啟動測試
    spring-boot學習:十五、spring-boot內建thymeleaf
  2. 其他

    1)如果前端用到layui,thymeleaf會與layui中的table存在沖突

col:[[]] 改成
col:[
        [
        ]
     ]
           

thymeleaf文法參考:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

繼續閱讀