SpringBoot整合Thymeleaf SpringBoot整合Thymeleaf的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot整合Thymeleaf SpringBoot整合Thymeleaf的方法

crazy戴夫   2021-04-21 我要评论

简介:

  在目前的企业级应用开发中 前后端分离是趋势,但是视图层技术还占有一席之地, Spring Boot 对视图层技术提供了很好的支持,官方推荐使用的模板引擎是 Thymeleaf 不过像 FreeMarker 也支持, JSP 技术在这里并不推荐使用。

  Thymeleaf 是新一代 Java 模板引擎,类似于 Velocity、FreeMarker 等传统 Java 模板引擎。与传统 Java 模板引擎不同的是 Thymeleaf 支持 HTML 原型,既可 以让前端工程师在浏览器中直接打 开查看样式,也可以让后端工程师结合真实数据查看显示效果。 同时, Spring Boot 提供了 Thymeleaf 自动 配置解决方案,因此Spring Boot 中使用 Thymeleaf 常方便。

1.引入依赖:

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

2.application.properties

#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=true
#是否检查模板是否存在,默认为true
spring.thymeleaf.check-template=true
#是否检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true
#模板文件编码
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件后缀
spring.thymeleaf.suffix=.html

3.创建实体类和controller类

public class Book {
  private Integer id;
  private String name;
  private String author;
  //省略getter/setter
}
@Controller
public class BookController {
  @GetMapping("/books")
  public ModelAndView books() {
    List<Book> books = new ArrayList<>();
    Book b1 = new Book();
    b1.setId(1);
    b1.setAuthor("罗贯中");
    b1.setName("三国演义");
    Book b2 = new Book();
    b2.setId(2);
    b2.setAuthor("曹雪芹");
    b2.setName("红楼梦");
    books.add(b1);
    books.add(b2);
    ModelAndView mv = new ModelAndView();
    mv.addObject("books", books);
    mv.setViewName("books");
    return mv;
  }
}

4.html文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>图书列表</title>
</head>
<body>
<table border="1">
  <tr>
    <td>图书编号</td>
    <td>图书名称</td>
    <td>图书作者</td>
  </tr>
  <tr th:each="book:${books}">
    <td th:text="${book.id}"></td>
    <td th:text="${book.name}"></td>
    <td th:text="${book.author}"></td>
  </tr>
</table>
</body>
</html>

5.结果:

总结

以上所述是小编给大家介绍的SpringBoot整合Thymeleaf的方法,希望对大家有所帮助!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们