SpringBoot:thymeleaf粗解

thymeleaf 百里香的叶片            

thymeleaf可以支持动态页面,即模板+数据。如下,html中的h1标签并不写死,而是可以在mode中动态设置的。

SpringBoot在pom.xml中引入该引擎时,可以不用指定版本号,其他的也不用指定,自动会配置好。 SpringBoot通过一个个×××AutoConfiguration实现自动装配,thymeleaf也有一个thymeleafAutoConfiguration,如果要修改默认的属性值,那么在.properties文件中通过prefix+属性的方式修改。

下面以实例展示thymeleaf模板+数据的用法。

1.新建一个springBoot web工程

2.在pom.xml中引入thymeleaf依赖

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

3.在thymeleafAutoconfiguration中,可以发现,其默认格式是.html,默认放置在templates目录下。

    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";

所以接下来在templates目录下新建一个result.html的thymeleaf文件,进入thymeleaf官网的tutorial中,将提供的简单示例代码复制进result.html中。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head>
<body>
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
</body>
</html>

稍作修改,去掉meta和link,保留body并且将#{home.welcome}修改成${welcome}

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Good Thymes Virtual Grocery</title>
</head>
<body>
    <p th:text="${welcome}">Welcome to our grocery store!</p>
</body>
</html>

4.新建一个controller,响应请求。

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class BootController {

    @RequestMapping("/request")
    public String request(Map<String,Object> map){
        map.put("welcome","WelcomeToThymeleaf");//给${welcome}赋值welcomeToThymeleaf
        return "result";
    }
}

结果:<p th:text="${welcome}">Welcome to our grocery store!</p>中的Welcome to our grocery store!将被替换成为${welcome}的内容。

 

目录结构:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章