三、thymeleaf的使用

1、简介

thymleaf是一个基于html的页面模板,springboot极力推荐使用它,代替jsp。

API地址:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf

 

2、使用

1)添加依赖

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

2)在templates下添加一个html,将文档声明为thymleaf文档:

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

3)写一个控制器

package com.biniu.controller;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lay
 * @date 2018/4/15.
 * @time 12:53
 */
@Controller
public class IndexController {

    @RequestMapping(value = {"", "index"})
    public String index(HttpServletRequest request, Model model) {
        // 属性
        model.addAttribute("properties", "properties value");
        // 对象
        Map<String, Object> person = new HashMap<>();
        person.put("name", "lay");
        model.addAttribute("person", person);
        // 列表
        List<Map<String, Object>> persons = new ArrayList<>();
        persons.add(person);
        persons.add(person);
        persons.add(person);
        model.addAttribute("persons", persons);
        // request
        request.setAttribute("requestAttribute", "requestValue");
        // session
        request.getSession().setAttribute("sessionAttribute", "sessionValue");
        return "index";
    }
}

4)thymleaf基本功能使用示例

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>welcome</title>
    <!--引入资源-->
    <link rel="stylesheet" th:href="@{/css/index.css}"/>
</head>
<body>

属性:
<div th:text="${properties}"></div>
<hr/>

对象:
<div th:text="${person.name}"></div>
<hr/>

if:
<div th:if="${1 <= 2}">if true</div>
<hr/>

switch-case:
<div th:switch="1">
    <div th:case="1">case 1</div>
    <div th:case="2">case 1</div>
    <div th:case="3">case 1</div>
    <div th:case="4">case 1</div>
</div>
<hr/>

遍历:
<div th:each="item, stat: ${persons}">
    <span th:text="${item.name}"></span>:&nbsp;<span th:text="${stat.index}"></span>
</div>
<hr/>

跳转:
<a th:href="@{http://www.baidu.com}">百度</a>
<hr/>

图片:
<img th:src="@{https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=708140547,444241267&fm=27&gp=0.jpg}" alt="" style="display: block;width: 100px;height: 100px;">
<hr/>

request取值:
<div th:text="${requestAttribute}"></div>
<hr/>

session取值:
<div th:text="${session.sessionAttribute}"></div>
<hr/>
</body>
</html>

 

posted @ 2018-04-15 13:55  __lay  阅读(339)  评论(0编辑  收藏  举报