Spring Boot+Thymeleaf進行Web開發
導航
在Java Web專案開發中,我們通常使用JSP頁面來做客戶端介面的開發,但是JSP在內嵌的Servlet容器中執行有一些問題,內嵌的Tomcat、Jetty不支援以jar形式執行JSP,所以Spring Boot中提供了很多模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity、Mustache,而Spring Boot推薦使用Thymeleaf,本文也是主要記敘使用Thymeleaf進行Web開發的方法。
什麼是模板引擎?
在Web開發中,我們使用模板引擎支援的頁面檔案型別進行介面開發,並且通常我們可以在頁面檔案中使用一些動態的標籤在實現資料的動態繫結,在程式執行時,模板引擎會按照路徑找到我們構建的頁面檔案並讀取,然後處理這些動態繫結的資料,處理完成後返回最終需要展示的頁面,最終Web程式將這個頁面展示給使用者。
在這個過程中,模板引擎的作用可以簡單概述:
訪問模板 => 按照模板進行資料繫結等操作 => 返回頁面
使用Spring Boot+Thymeleaf進行Web開發
本文所使用的Spring Boot版本為2.0.0.Release
一、引入必須的啟動器
spring-boot-starter-thymeleaf啟動器中已經將Spring MVC的檢視解析器配置為Thymeleaf了,所以不需要我們再手動配置
<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>
二、構建Thymeleaf需要的模板
Thymeleaf支援直接使用html作為模板,在Maven專案中它預設的模板檔案訪問路徑是src/main/resources/templates。
暫時不清楚Thymeleaf預設的靜態檔案路徑,可以設定Spring的靜態資源位置,然後Thymeleaf就可以使用該路徑獲取到專案的靜態資原始檔,對於maven工程,此處的classpath對應的是src/main/resources。
spring.resources.static-locations=classpath:/statics/
- study.html
<!DOCTYPE html>
<!--要使用的Thymeleaf提供的動態標籤,需要引入thymeleaf的標籤庫-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello world.<br>
<!--訪問model中的資料並進行文字拼接-->
<label>my name is [[${map.name}]]</label><br>
<!--訪問model中的資料,並將當前元素的text初始化為該值-->
<label th:text="${map.name}"></label>
<ul>
<!--迴圈遍歷初始化資料-->
<li th:each="fruit:${fruits}">
<span th:text="${fruit}"></span>
</li>
</ul>
</body>
<!--引入js-->
<script type="text/javascript" src="/js/study.js"></script>
<script type="text/javascript" src="/layui-v2.4.3/layui/layui.js"></script>
</html>
還有很多的Thymeleaf標籤,可以在網上查詢,使用方法都類似。
三、構建Controller
@RequestMapping("/method2")
public ModelAndView studyMethod2(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("study");//初始化ModelAndView
Map<String, Object> map = new HashMap<>();
map.put("name", "marry");
List<String> arr = new ArrayList<>();
arr.add("apple");
arr.add("pear");
arr.add("banana");
//向ModelAndView新增資料,這些資料就是模板引擎用來向頁面繫結的資料
mav.addObject("fruits", arr);
mav.addObject("map", map);
return mav;
}
四、最終呈現的頁面:
五、禁用模板以及靜態資源的快取,以便除錯
spring.thymeleaf.cache=false