Thymeleaf使用環境搭建和簡單使用


Thymeleaf與JSP比較

與JSP相比,Thymeleaf模板是原生的,不依賴標簽庫,可以在接收原始的HTML的地方進行編輯和渲染。不與servlet規范耦合。JSP在內嵌的servlet容器上運行有一些問題(內嵌Tomcat,Jetty不支持jar形式運行JSP,Undertow不支持JSP),也就是說,springboot項目如果想使用JSP的話,必須放棄其內嵌的Tomcat。Spring Boot 提供大量的模板引擎(FreeMarker,Groovy,Thymeleaf,Velocity和Mustache),Spring Boot推薦使用Thymeleaf,Thymeleaf提供完美的Spring MVC支持。

非Spring Boot項目使用Thymeleaf環境

需要配置三個啟用Thymeleaf與Spring集成的Bean

  • ThymeleafViewResolver: 將邏輯視圖名稱解析為Thymeleaf模板視圖
  • SpringTemplateEngine: 處理模板並渲染結果
  • TemplateResolver:加載Thymeleaf模板

使用java配置:

    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
    
    @Bean
    public TemplateEngine templateEngine(TemplateResolver templateResolver){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
    
    @Bean
    public TemplateResolver templateResolver(){
        TemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }

使用xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <bean id="viewResolver" 
          class="org.thymeleaf.spring4.view.ThymeleafViewResolver"
          p:templateEngine-ref="templateEngine"/>
    
    <bean id="templateEngine"
          class="org.thymeleaf.spring4.SpringTemplateEngine"
          p:templateResolver-ref="templateResolver"/>
    
    
    <bean id="templateResolver"
          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"
          p:prefix="/WEB-INF/templates/"
          p:suffix=".html"
          p:templateMode="HTML5"/>
</beans>

Spring Boot使用Thymeleaf

  • 新建Spring Boot項目
  • 在創建時添加thymeleaf依賴,或者是創建完畢在pom.xml文件中添加thymeleaf依賴

pom.xml

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

在application.properties中配置

//關閉緩存
spring.thymeleaf.cache=false

Thymeleaf的簡單使用

新建html頁面

傳統項目放在配置的位置

springboot項目一般放在static/templates下

首先添加thymeleaf的命名空間

xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>index</title>
</head>
<body>

</body>
</html>

測試

在static里面創建css/style.css,用來測試讀取靜態資源

.title{
    color: red;
    font-size: larger;
}

創建javaBean

public class Student {

    private String name;

    private Double score;

    public Student(String name, Double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }
}

准備測試數據

@Controller
@SpringBootApplication
public class ThymeleafdemoApplication {

    @RequestMapping("/")
    public String index(Model model){

        Student stu = new Student("stu_1", 34.5d);

        List<Student> studentList1 = new ArrayList<>();
        Student s1 = new Student("list-1", 23.5d);
        Student s2 = new Student("list-2", 22.5d);
        Student s3 = new Student("list-3", 21.5d);
        studentList1.add(s1);
        studentList1.add(s2);
        studentList1.add(s3);

        //空的list
        List<Student> studentList2 = new ArrayList<>();

        model.addAttribute("stu", stu);
        model.addAttribute("studentList1", studentList1);
        model.addAttribute("studentList2", studentList2);


        return "index";
    }


    public static void main(String[] args) {
        SpringApplication.run(ThymeleafdemoApplication.class, args);
    }

}

在templates下創建index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>index</title>

    <!--添加css-->
    <link rel="stylesheet" type="text/css" th:href="@{css/style.css}"/>
</head>
<body>

<!--測試css資源引用 red:成功找到css資源-->
<div class="title">測試1</div>
<br/>

<h3>下面是獲取stu對象的值:</h3>
<div>
    stu姓名:
    <span th:text="${stu.name}">獲取不到</span>
    stu成績:
    <span th:text="${stu.score}">獲取不到</span>
</div>

<br/>

<div>
    <h3>下面是獲取list的值</h3>
    <div th:if="${ #lists.isEmpty(studentList2)}">
        這是空列表
    </div>

    <div th:if="${ not #lists.isEmpty(studentList1)}">
        <h4>列表內容如下:</h4>
        <div th:each="stu:${studentList1}">
            學生姓名:
            <span th:text="${stu.name}">沒有數據</span>
            成績:
            <span th:text="${stu.score}">沒有數據</span>
        </div>
    </div>
</div>

</body>
</html>

測試結果:
1.png

thymeleaf模板編寫時需要嚴格的按照html規范!!!

補充

避免thymeleaf的html代碼檢查過嚴

在pom.xml文件添加依賴:

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.21</version>
</dependency>

在application.properties配置thymeleaf的mode

spring.thymeleaf.mode=LEGACYHTML5

內容參考《Spring實戰》、《Java EE開發顛覆者 Spring Boot實戰》


免責聲明!

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



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