欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringBoot整合Thymeleaf的方法

时间:2021-03-27 09:29:41|栏目:JAVA代码|点击:

简介:

  在目前的企业级应用开发中 前后端分离是趋势,但是视图层技术还占有一席之地, 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的方法,希望对大家有所帮助!

上一篇:Java特性队列和栈的堵塞原理解析

栏    目:JAVA代码

下一篇:Java Bean与Map之间相互转化的实现方法

本文标题:SpringBoot整合Thymeleaf的方法

本文地址:http://www.codeinn.net/misctech/88897.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有