Spring boot 中使用 Thymeleaf

来源:互联网 发布:白金网络加速器下载 编辑:程序博客网 时间:2024/05/22 12:26

Thymeleaf  是一个java类库,他是一个xml/xhtml/html5的模板引擎,可使用在MVC的Web应用的View层.

创建springboot项目,并引入Thymeleaf:



下面附上部分代码


SomunsAppcation.java

package net.somuns.somuns;import net.somuns.somuns.model.Dog;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;@Controller@SpringBootApplicationpublic class SomunsApplication {@RequestMapping("/")public String index(Model model){ArrayList<Dog> dogList = new ArrayList<>();dogList.add(new Dog("小黄","黄色",1));dogList.add(new Dog("小红","黑色",3));dogList.add(new Dog("旺财","棕色",2));dogList.add(new Dog("花花","白色",1));model.addAttribute("dogList",dogList);model.addAttribute("dog",new Dog("泰迪","棕色",2));return "index";}public static void main(String[] args) {SpringApplication.run(SomunsApplication.class, args);}}

index.html

<html xmlns:th="http://www.thymeleaf.org"><head>    <meta content="text/html" charset="UTF-8"/>    <meta http-equiv="X-UA-Compatible" content="IE=edge" />    <meta name="viewport" content="width=device-width, initial-scale=1" />    <link th:href="@{css/bootstrap.css}" rel="stylesheet" />    <title>Thymeleaf</title></head><body><div class="panel panel-primary">    <div class="panel-heading">        <h3 class="panel-title">单个对象—model</h3>    </div>    <div class="panel-body">        <span th:text="${dog.name}"></span>    </div></div><div th:if="${not #lists.isEmpty(dogList)}">    <div class="panel panel-primary">        <div class="panel-heading">            <h3 class="panel-title">列表-集合</h3>        </div>        <div class="panel-body">            <ul class="list-group">                <li class="list-group-item" th:each="dog:${dogList}">                    <span th:text="${dog.name}"></span>                    <span th:text="${dog.color}"></span>                    <span th:text="${dog.age}"></span>                    <button class="btn" th:onclick="'getName(\''+${dog.name}+'\');'">获得名字</button>                </li>            </ul>        </div>    </div></div><script th:src="@{js/jquery-3.2.1.min.js}" type="text/javascript"></script><script th:src="@{js/bootstrap.min.js}"></script><script th:inline="javascript">    var dog_ = [[${dog}]];    console.log(dog_.name+"/"+dog_.color);    function getName(name){        alert(name);    }</script></body></html>

程序成功后:

附上码云实例代码:https://gitee.com/xushoulai/somuns-demo/tree/master/springboot-thymeleaf

原创粉丝点击