SpringBoot使用thymeleaf

来源:互联网 发布:php二合一网站 编辑:程序博客网 时间:2024/06/16 14:31

thymeleaf音译:塞姆理符

1.新建SpringBoot项目,选择thymeleaf依赖,会自动导入

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

2.创建POJO

package com.cvsea;public class Person {    private String name;    private Integer age;    public Person(String P_Name,Integer P_Age)    {        this.name=P_Name;        this.age=P_Age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

3.创建演示页面,thymeleaf模板引擎页面放在src/main/resources/templates下。

index.html

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"/><title>Insert title here</title></head><body><div>    <h3>访问model</h3>    <span th:text="${singlePeson.name}"></span></div><div th:if="${not #lists.isEmpty(people)}">    <h3>访问列表</h3>    <ul>        <li th:each="person:${people}">            <span th:text="${person.name}"></span>            <span th:text="${person.age}"></span>            <button th:onclick="'getName(\''+${person.name}+'\')'">获取名字</button>        </li>    </ul></div><script th:inline="javascript">var single=[[${singlePeson}]]console.log(single.name+"/"+single.age);function getName(name){    console.log(name);}</script></body></html>

4.注入数据

package com.cvsea;import java.util.ArrayList;import java.util.List;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;@Controller@SpringBootApplicationpublic class Learning1Application {    @RequestMapping("/")    public String hello(Model model)    {        Person person=new Person("pxs",26);        model.addAttribute("singlePeson",person);        List<Person> people=new ArrayList<Person>();        people.add(new Person("pxs",26));        people.add(new Person("nxy",26));        people.add(new Person("lgp",26));        model.addAttribute("people",people);        return "index";     }    public static void main(String[] args) {        SpringApplication.run(Learning1Application.class, args);    }}

5.运行效果

这里写图片描述

原创粉丝点击