Thymeleaf 使用總結(一)
阿新 • • 發佈:2018-11-02
模板引擎
模板的誕生是為了將顯示與資料分離,模板技術多種多樣,但其本質是將模板檔案和資料通過模板引擎生成最終的HTML程式碼。
模板技術並不是什麼神祕技術,乾的是拼接字串的體力活。模板引擎就是利用正則表示式識別模板標識,並利用資料替換其中的識別符號。
Thymeleaf 使用總結
- Thymeleaf 是一個Java類庫,它是一個xml/xhtml/html5的模板引擎,可以作為MVC的web應用的View層。
- Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。
是Springboot推薦使用的模板引擎。 - spring-boot下,預設約定了Controller試圖跳轉中thymeleaf模板檔案的字首prefix是”classpath:/templates/”,字尾suffix是”.html”
1、非嚴格宣告
在預設配置(spring.thymeleaf.mode的預設值是HTML5)下,thymeleaf對.html的內容要求很嚴格
因此,改為LEGACYHTML5可以得到一個可能更友好親切的格式要求。建議增加下面這段:
spring.thymeleaf.mode = LEGACYHTML5 或yml格式檔案 #thymeleaf thymeleaf: mode: LEGACYHTML5 cache: false
pom.xml中增加
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
2、th標籤整理
1)簡單表示式
- 變量表達式 ${……}
- 選擇/星號表示式 *{……} 選擇表示式一般跟在th:object後,直接取object中的屬性。
- 文字國際化表示式 #{……} 呼叫國際化的welcome語句,國際化資原始檔如下
- URL表示式 @{……}
2)表示式基本物件
在上下文變數評估OGNL表示式時,一些物件表示式可獲得更高的靈活性。這些物件將由#號開始引用。
- #ctx: 上下文物件.
- #vars: 上下文變數.
- #locale: 上下文語言環境.
- #httpServletRequest: (僅在web上文)HttpServletRequest 物件.
- #httpSession: (僅在web上文) HttpSession 物件.
3)表示式功能物件
- #dates:java.util.Date物件的實用方法。
- #calendars:和dates類似, 但是 java.util.Calendar 物件.
- #numbers: 格式化數字物件的實用方法。
- #strings: 字元創物件的實用方法: contains, startsWith, prepending/appending等.
- #objects: 對objects操作的實用方法。
- #bools: 對布林值求值的實用方法。
- #arrays: 陣列的實用方法。
- #lists: list的實用方法。
- #sets: set的實用方法。
- #maps: map的實用方法。
- #aggregates: 對陣列或集合建立聚合的實用方法。
- #messages: 在表示式中獲取外部資訊的實用方法。
- #ids: 處理可能重複的id屬性的實用方法 (比如:迭代的結果)。
3、靜態資源引用
<link rel="stylesheet" th:href="@{/css/base1.css}" />
<script type="text/javascript" th:src="@{/js/common.js}" charset="UTF-8"></script>
4、th:include
th:include中的引數格式為templatename::[domselector]
其中templatename是模板名(如footer),domselector是可選的dom選擇器。如果只寫templatename,不寫domselector,則會載入整個模板。
<div th:include="footer :: copyright"></div>
th:include 是載入模板的內容,而th:replace則會替換當前標籤為模板中的標籤
5、th:text
<p th:text="${collect.description}">description</p>
5、th:each
<li th:each="book:${booklist}" th:text="${book.bookname}">三體</li>
6、th:inline
<script type="text/javascript" th:inline="javascript">
可在內聯js中使用變數,例如 [[${booklist}]]形式;
7、form表單提交及validation驗證
<form action="#" th:action="@{/book/save}" method="post" th:object="${book}" method="post">
<div>
<label>書名:</label>
<input type="text" autofocus="autofocus" name="bookname" placeholder="請輸入書名" th:field="*{bookname}"/>
<small th:if="${#fields.hasErrors('bookname')}" th:errors="*{bookname}">錯誤提示</small>
</div>
</form>
需要注意的是標籤裡使用了“th:object=”${book}” ”,中使用“th:field=”*{bookname}””,可是實現欄位自動繫結,
但是在對應controller中需要新增下面方法,否則th:field會出錯,
@ModelAttribute
Book setBook () {
return new Book ();
}
對應controller中方法如下:
@RequestMapping(value = "/save",method = RequestMethod.POST)
public String saveBook(@Valid @ModelAttribute(value="book") Book book, BindingResult result, HashMap<String, Object> map){
if(result.hasErrors()){
map.put("MSG", "出錯啦!");
}else{
map.put("MSG", "提交成功!");
bookService.insertOne(book);
}
map.put("booklist",bookService.findAll(1,200));
return "/addbook";
}
實體類中可新增約束,如果違反了約束,則無法提交,並且可以用th:errors顯示出錯資訊
public class Book {
private Integer bookid;
@NotEmpty(message="作者不能為空")
private String author;
@NotEmpty(message="書名不能為空")
private String bookname;
@Size(max = 4, message="型別名不能超過四個字")
private String booktype;
}
如果表單中要提交日期,controller中可以新增日期轉換方法,防止資料型別轉換失敗,無法插入資料庫。
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
//轉換日期
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor為自定義日期編輯器
}