SpringBoot_Themeleaf

weixin_34208283發表於2016-12-14

http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
http://blog.csdn.net/u012706811/article/details/52185345
springboot有很多預設配置
預設頁面對映路徑:classpath:/templates/*.html
靜態檔案路徑為 classpath:/static/

springboot預設使用themeleaf模板引擎
pom.xml新增依賴

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

在application.properties中配置themeleaf模板解析器屬性

spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#開發時關閉快取,不然沒法看到實時頁面
# Allow Thymeleaf templates to be reloaded at dev time    
spring.thymeleaf.cache=false    

注意:在spring-boot下,預設約定了Controller試圖跳轉中thymeleaf模板檔案的字首prefix是”classpath:/templates/”,字尾suffix是”.html”

新增themeleaf名稱空間

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

頁面demo

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello, ' + ${name} + '!'" ></p>
</body>
</html>

Controller層

@Controller
@RequestMapping("/themeleaf")
public class HelloThemeController{
    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String helloTheme(Model model){
        model.addAttribute("name", "world");
        return "/hello";
    }
}