springboot 整合thymeleaf 书笔记
-
pom.xml依赖添加
-
1 <!--引入thymeleaf--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-thymeleaf</artifactId> 5 </dependency> 6 7 <!--引入谷歌的guava--> 8 <dependency> 9 <groupId>com.google.guava</groupId> 10 <artifactId>guava</artifactId> 11 <version>19.0</version> 12 </dependency> 13 14 <dependency> 15 <groupId>org.springframework.boot</groupId> 16 <artifactId>spring-boot-starter-web</artifactId> 17 </dependency>
-
-
yml的配置
-
1 spring: 2 thymeleaf: 3 cache: true 4 check-template: true 5 check-template-location: true 6 encoding: utf-8 7 prefix: classpath:/templates/ 8 servlet: 9 content-type: text/html 10 suffix: .html
-
-
实体类的创建
-
1 @Data 2 @AllArgsConstructor 3 public class Book { 4 private Integer id; 5 private String name; 6 private String author; 7 }
-
-
controller层
-
1 @Controller 2 public class BookController { 3 @GetMapping("/book") 4 public ModelAndView book(){ 5 ModelAndView mv = new ModelAndView(); 6 // 谷歌的guava 集合方法 7 List<Book> mybook = Lists.newArrayList(new Book(1,"小李子","小明"), 8 new Book(2,"小乌龟","挽歌")); 9 mv.addObject("mybook",mybook); 10 mv.setViewName("books"); 11 return mv; 12 } 13 }
-
-
html视图
-
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>图书列表</title> 7 </head> 8 <body> 9 <table border="1"> 10 <tr> 11 <td>图书编号</td> 12 <td>图书名称</td> 13 <td>图书作者</td> 14 </tr> 15 <tr th:each="book:${mybook}"> 16 <td th:text="${book.id}"></td> 17 <td th:text="${book.name}"></td> 18 <td th:text="${book.author}"></td> 19 </tr> 20 </table> 21 </body> 22 </html>
-
templates->xxx.html
-
-
启动项目(http://localhost:8080/book)
作者:以罗伊
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。