Spring Boot教程(4)-日誌配置-logback和使用。
Spring Boot教程(5)-web應用開發-模板引擎Thymeleaf
Spring Boot教程(8)-使用SQL關係型數據庫-JdbcTemplate
Spring Boot教程(9)-Spring-data-jpa
Spring Boot教程(10)-使用SQL關係型數據庫-h2嵌入式數據庫的使用
Spring Boot教程(12)-redis緩存設置,冪等性防重複提交
Spring Boot教程(13)-使用異步消息服務-JMS(ActiveMQ)
Spring Boot教程(14)-使用異步消息服務-AMQP(RabbitMQ)
Spring Boot教程(16)-集成Druid阿里數據庫連接池
Spring Boot教程(17)-Spring Boot集成Swagger
一:模板引擎的介紹:
FreeMarker
Thymeleaf
Velocity (1.4版本之後棄用,Spring Framework 4.3版本之後棄用)
Groovy
Mustache
注:jsp應該儘量避免使用,原因如下:
- jsp只能打包爲:war格式,不支持jar格式,只能在標準的容器裏面跑(tomcat,jetty都可以)
- 內嵌的Jetty目前不支持JSPs
- Undertow不支持jsps
- jsp自定義錯誤頁面不能覆蓋spring boot 默認的錯誤頁面
Thymeleaf 是一個優秀的、面向Java 的XML慶HTML/HTML5 頁面模板,具有豐
富的標籤語言和函數。因此,在使用Spring Boot 框架進行頁面設計時, 一般都會選擇Thymeleaf 模板。
一:Thymeleaf模板引擎使用:
1;引入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2:配置文件:
server.port=8081
###ThymeLeaf配置
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
spring.thymeleaf.mode=HTML5
#編碼 可不用配置
spring.thymeleaf.encoding= UTF-8
#開發配置爲false,避免修改模板還要重啓服務器
spring.thymeleaf.cache= false
#配置模板路徑,默認是templates,可以不用配置
spring.thymeleaf.prefix=classpath:/templates
3;編寫代碼Controller
@RequestMapping("/thymeleaf")
public ModelAndView thymeleaf(){
User user = new User();
user.setName("wsj");
user.setAge(100);
ModelAndView mv = new ModelAndView();
mv.addObject("user", user);
mv.setViewName("/user/user.html");
return mv;
}
User文件:
package com.wsj.springbootdemo.bean;
/**
* 項目名稱:User;
* 類 名 稱:User;
* 類 描 述:TODO ;
* 創 建 人:Angus;
* 創建時間:2020/2/15 20:17;
*
* @version:1.0
**/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4:編寫魔板頁:在templates下的user文件夾建user.html測試頁面,內容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show User</title>
</head>
<body>
<table>
<tr>
<td>姓名</td>
<td>年齡</td>
</tr>
<tr>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
</body>
</html>
運行代碼查看結果:
至此;templates模板在SpringBoot中使用結束
至於templates的語法和使用可以參考官網文檔https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
本文代碼github地址:https://github.com/itwsj/springbootdemo