现在的位置: 首页 > 编程语言 > 正文

SpringBoot整合Thymeleaf的方法

2020年02月18日 编程语言 ⁄ 共 1906字 ⁄ 字号 评论关闭

简介:

  在目前的企业级应用开发中 前后端分离是趋势,但是视图层技术还占有一席之地, 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,默认为truespring.thymeleaf.cache=true#是否检查模板是否存在,默认为truespring.thymeleaf.check-template=true#是否检查模板位置是否存在,默认为truespring.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}@Controllerpublic 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的方法,希望对大家有所帮助!

以上就上有关SpringBoot整合Thymeleaf的方法的相关介绍,要了解更多springboot, 整合, thymeleaf内容请登录学步园。

抱歉!评论已关闭.