本文章將介紹Thymeleaf標(biāo)準(zhǔn)表達(dá)式語(yǔ)法中的概念。
html
的字符串。在第一個(gè)div中顯示HTML轉(zhuǎn)義字符串,在第二個(gè)div
中顯示未轉(zhuǎn)義字符串。如果要上機(jī)實(shí)踐,請(qǐng)參考:Thymeleaf+SpringMVC5示例項(xiàng)目。這里不再重復(fù)創(chuàng)建項(xiàng)目的過(guò)程,這里將只介紹如何使用Thymeleaf
標(biāo)準(zhǔn)表達(dá)式和標(biāo)簽。
這里創(chuàng)建一個(gè)Maven Web項(xiàng)目: thymeleaf-tutorials ,其目錄結(jié)構(gòu)如下所示 -
控制器類的實(shí)現(xiàn):MyController.java -
package com.yiibai.spring.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.yiibai.spring.bean.Product;
@Controller
public class MyController {
@GetMapping("/")
public String index(Model model) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
model.addAttribute("product", product);
return "index";
}
@GetMapping("/escape")
public String escape(Model model) throws ParseException {
String html = "Welcome to our <b>fantastic</b> grocery store!";
model.addAttribute("html", html);
return "escape";
}
}
模板文件的實(shí)現(xiàn):/webapp/WEB-INFO/views/escape.html -
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf示例</title>
</head>
<body>
<h2>Spring MVC5 + Thymeleaf 字符串轉(zhuǎn)義示例</h2>
<div th:text="${html}">Some escaped text</div>
<div th:utext="${html}">Some unescaped text</div>
</body>
</html>
運(yùn)行上面項(xiàng)目,在瀏覽器中顯示效果如下 -