1. 程式人生 > >springboot使用thymeleaf完成資料的頁面展示

springboot使用thymeleaf完成資料的頁面展示

上一篇介紹了使用jsp完成資料的頁面展示 ,但是springboot並不推薦使用jsp,會產生很多問題。官方推薦使用thymeleaf,這裡我們將上一篇的jsp頁面展示修改為使用thymeleaf,通過對比來熟悉thymeleaf,其實改動的地方並不大。

第一篇springboot入門時介紹了專案的大致結構,當時圖省事所有的類都放在一個包中,這裡略做調整,然後再resource下新建資料夾存放thymeleaf模板,使用springboot生成工程時應該會預設有這幾個資料夾,此時專案結構大致如下:


thymeleaf新增依賴

<dependency>
      	<groupId>org.springframework.boot</groupId>
     	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

查詢介面(接上一篇,基本沒變)

/**
	 * @return
	 * 查詢全部資訊
	 */
	@RequestMapping("/list")
	public ModelAndView  itemsList() {
		String sql = "select * from items";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		ModelAndView mav = new ModelAndView("items");
		mav.addObject("list", list);
		return mav;
	}

對應thymeleaf 模板頁面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>springboot學習</title>
</head>

<body>
	<div th:each="item : ${list}">
		<h1 th:text="${{item.title}}"></h1>
		<p><a th:text="${{item.name}}"></a></p>
		<p><a th:text="${{item.detail}}"></a></p>
	</div>
</body>
</html>

此時我們執行http://localhost:8080/items/list,和jsp輸出結果無異


程式碼很便捷,和上一篇的jsp遍歷list資料差別不大,通過對比也能很好的掌握thymeleaf 的用法,這裡用 th:each 放入需要遍歷的內容,以及定義變數名;在其他標籤中用th:text來展示內容,寫法也很容易理解。

新增介面

/**
	 * 新增資料
	 * @param items
	 * @return
	 */
	@RequestMapping("/add")
	public @ResponseBody boolean  addItems(Items items) {
		String sql = "insert into items (title,name,detail) value (?,?,?)";
		Object args[] = {items.getTitle(),items.getName(),items.getDetail()};  
		int temp = jdbcTemplate.update(sql, args); 
		if(temp > 0) {
			return true;
		}
		return false;
	}


對應的thymeleaf 模板頁面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>springboot學習</title>
<script th:src="@{/js/jquery-1.8.3.js}"></script>
</head>
<body>
	<div>
    	<form name="addItems">
  			<input type="text" name="title" />
  			<input type="text" name="name" />
  			<input type="text" name="detail" />
  			<input type="button" value="提交" onclick="return add()"/>
  		</form>
    </div>
</body>
<script type="text/javascript">
		function add(){
			var title = addItems.title.value;
			var name = addItems.name.value;
			var detail = addItems.detail.value;
			 $(document).ready(function(){
				$.post("add",
				{"title":title,"name":name,"detail":detail},
				function(data){
	 				if(data == true){
	 					alert("新建成功");
	 				}
	 				if(data == false){
	 					alert("新建失敗");
	 				}
	 			});
			});
		}
	</script>
</html>

表單提交方式的寫法(更多可以參考:http://itutorial.thymeleaf.org;很全面)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Thymeleaf tutorial: exercise 12</title>
        <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
        <meta charset="utf-8" />
    </head>
    <body>
        <h1>Thymeleaf tutorial - Solution for exercise 12: forms</h1>
        <h2>Customer edition</h2>
        <form action="saveCustomer.html" th:action="@{/exercise12/saveCustomer.html}" th:object="${customer}" method="post">
            <input type="hidden" th:field="*{id}" />
            
            <label for="firstName">First name:</label>
            <input type="text" th:field="*{firstName}" value="John" />
            
            <label for="lastName">Last name:</label>
            <input type="text" th:field="*{lastName}" value="Wayne" />
            
            Genre:
            <div th:each="gender : ${genders}" class="radio">
                <input type="radio" th:value="${gender}" th:field="*{gender}" />
                <label th:for="${#ids.prev('gender')}" th:text="${gender.description}">Male</label>
            </div>
            <div th:remove="all" class="radio">
                <input type="radio" />
                <label>Female</label>
            </div>
            
            <label for="paymentMethod">Payment method:</label>
            <select th:field="*{paymentMethod}" th:remove="all-but-first">
                <option th:each="paymentMethod : ${paymentMethods}"
                        th:value="${paymentMethod}" th:text="${paymentMethod.description}">Credit card</option>
                <option>Another payment method</option>
                <option>Another payment method</option>
            </select>
            
            <label for="balance">Balance (dollars):</label>
            <input type="text" th:field="*{balance}" size="10" value="2500" />
            
            <input type="submit" />
        </form>
    </body>
</html>


這裡列舉常見用法:

1、在html頁面中引入thymeleaf名稱空間:<html xmlns:th=http://www.thymeleaf.org></html>,此時在html模板檔案中動態的屬性使用th:名稱空間修飾 ;

2、引用靜態資原始檔:比如CSS和JS檔案,語法格式為“@{}”,比如引用resource/static/js下的jquery檔案:<script th:src="@{/js/jquery-1.8.3.js}"></script>;

3、頁面顯示時將時間的格式化: ${#dates.format(worker.updateTime,'yyyy-MM-dd HH:mm:ss')} 表示將時間格式化為”yyyy-MM-dd HH:mm:ss”;

4、字串拼接:比如拼接這樣一個URL:/items/delete/{itemId} 寫法是:th:href="'/items/delete/' + ${items.id }"

5、for迴圈遍歷出資料,以上查詢全部中已有例子:<div th:each="item : ${list}"><h1 th:text="${{item.title}}"></h1></div>