Springboot整合Thymeleaf框架——SpringBoot學習

一、pom 文件引入Thymeleaf

  在原 SpringBoot 項目中的 POM 文件中加入 Thymeleaf 座標,如果不知道座標可以從 Maven 中央庫查詢 http://mvnrepository.com/。當然,如果項目沒有使用 Maven ,那就需要導入 Thymeleaf 的Jar ,包括有 thymeleaf-spring5.jar ,和 thymeleaf-extras-java8time.jar

<!-- 引入thymeleaf的依賴包. -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、Controller

package com.controller;

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

/**
* @Description springboot整合Thymeleaf
* @author 歐陽
* @since 2019年4月10日 下午5:20:49
* @version V1.0
*/
@Controller
public class IndexThymeleafController {
	
	@RequestMapping("/indexThymeleaf")
	public String indexThymeleaf(Model model) {
		
		model.addAttribute("title", "springboot整合Thymeleaf");
		
		return "indexThymeleaf";
	}
}

  注意:使用註解 @Controller 而不要使用 @RestController ,否則會將返回的視圖名解析成字符串返回到頁面。如果使用 @RestController 註解,則需要返回 ModelAndView

三、application.properties 配置

  在 application.properties 文件中添加下面配置:

### Thymeleaf  Configuration
spring.thymeleaf.cache=true
spring.thymeleaf.enable-spring-el-compiler=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html; charset=utf-8
spring.thymeleaf.check-template-location=true
spring.thymeleaf.check-template=true
spring.thymeleaf.suffix=.ftl

  上面的配置使用 application.yml 文件配置如下:

### Thymeleaf Configuration
spring:
  thymeleaf:
    cache: true
    enable-spring-el-compiler: true
    encoding: UTF-8
    suffix: .html
    check-template-location: true
    check-template: true
    servlet:
      content-type: text/html; charset=utf-8
 

  其實也可以不用添加配置,大部分用到的框架已經默認打開了,這裏只是爲了演示如果需要配置則按需配置,例如:如果模板需要用到 EL 表達式,則需要將spring.thymeleaf.enable-spring-el-compiler配置爲 true(支持)因爲spring的 EL 表達式默認是 false(不支持)。

四、HTML 文件

  當使用 Thymeleaf 模板引擎時,默認的模板配置路徑爲:src/main/resources/templates ,下面是使用默認的模板配置路徑新建文件 indexThymeleaf.html ,其的主要代碼如下所示。關於 Thymeleaf 的語法請參考文章 SpringBoot學習——Thymeleaf教程詳解

<body>
	<h3 th:text="${title}"></h3>
</body>

五、整合後結果

  瀏覽器訪問地址:http://localhost:8080/indexThymeleaf ,後效果圖如下:
springboot整合Thymeleaf

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章