SpringBoot入門之Thymeleaf的使用


在.net的MVC3 或更高版本等支持 Razor 的框架里使用cshtml,Razor是一種簡單的編程語法,用於在網頁中嵌入服務器端代碼.在使用springboot開發mvc時也有與.net類似的視圖引擎.
Spring Boot提供了大量的模板引擎,包含了FreeMarker,Groovy,Thymeleaf,Velocity和Mustache,Spring Boot中推薦使用Thymeleaf作為模板引擎,因為Thymeleaf提供了完美的Spring MVC的支持。Thymeleaf是一個java類庫,它是一個xml/xhtml/html5的模板引擎,可以作為MVC的Web應用的View層。Thymeleaf還提供了額外的模塊與Spring MVC集成,所以我們可以使用Thymeleaf完全替代JSP。
一、Thymeleaf配置
Thymeleaf有哪些屬性可以配置呢,我們可以在org.springframework.boot.autoconfigure.thymeleaf下的ThymeleafProperties.class找到屬性,springboot約定大於配置,所以在ThymeleafProperties.class中也都有默認值,如果我們想改變默認值可以在application.properties設置。這里用的都是它的默認值。默認路徑在templates下,文件是html文件。

 

二、項目引入Thymeleaf

這里還是在上一springboot博客的例子基礎上進行修改,這里需要在pom.xml引入Thymeleaf,這里要注意一下,由於用的是spring5,如果引入的Thymeleaf版本不正確就可能會報錯,而且不同的spring引入Thymeleaf的artifactId也不一樣。

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>

同時如果在html頁面使用還需要在html增加一行

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

三、測試

這里創建了一個Controller和一個html.Thymeleaf的屬性都是用的默認的屬性值,如果需要改變可以在resources/application.properties下更改,前綴名是spring.thymeleaf。

package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


//@RestController
@Controller
public class HelloController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(Model model) {
        model.addAttribute("name", "Cuiyw");
        return "hello";
    }
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${name} + '!'" ></p>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM