spring boot - thymeleaf

135 阅读2分钟

thymeleaf使用

spring boot结合thymeleaf 可以结合模板来整合HTML,使用原生的html作为视图,就不需要jsp页面,该用法类似之前的jsp+jstl里面的使用的el表达式

spring boot 整合thymeleaf

创建maven工程
pom.xml里添加依赖

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.6.RELEASE</version>
</parent>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
  <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.6</version>
  </dependency>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.0.6.RELEASE</version>
  </dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.0.6.RELEASE</version>
</dependency>

在handler里

@Controller
@RequestMapping("/index")
public class IndexHandler {
    @GetMapping("/index")
    public String index(Model model){
        System.out.println("index");
        List<Student> list = new ArrayList<>();
        list.add(new Student(1l,"ff",34));
        list.add(new Student(2l,"4f",24));
        list.add(new Student(3l,"fdf",54));
        model.addAttribute("list",list);
        return "index";
    }
}

创建student类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private long id;
    private String name;
    private int age;
}

在resources底下创建application.yml

server:
  port: 8080
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML5
    encoding: UTF-8

注意这里的classpath是当前目录下的templates
所以要创建一个templates目录 底下写index.html
index.html

<!DOCTYPE html>
<html lang="en">
<html xmlns="http://www.thymeleaf.org"></html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello</h1>
<table>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>age</th>
    </tr>
    <tr th:each="student:${list}">
        <td th:text="${student.id}"></td>
        <td th:text="${student.name}"></td>
        <td th:text="${student.age}"></td>
    </tr>
</table>
</body>
</html>

另外,如果希望html直接能通过地址栏访问,就在resources底下创建一个static文件夹,将html放在该目录下。