首先,我们在pom.xml中添加如下内容
<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>
|
然后创建一个Book 类
package com.example.demo;
import org.springframework.stereotype.Component;
@Component public class Book { private Integer id; private String name; private String author;
public Integer getId() { return id; }
public String getName() { return name; }
public String getAuthor() { return author; }
public void setId(Integer id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setAuthor(String author) { this.author = author; }
@Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + '}'; }
}
|
然后创建一个BookController 控制器
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList; import java.util.List;
@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; } }
|
接下里在resource 下的template 中新建一个books.html
<!DOCTYPE html> <html lang="en"> <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.author}"></td> <td th:text="${book.name}"></td> </tr> </table> </body> </html>
|
在application.properties中添加如下内容
spring.thymeleaf.cache=false spring.thymeleaf.check-template=true spring.thymeleaf.check-template-location=true spring.thymeleaf.encoding=utf-8 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.servlet.content-type=text/html spring.thymeleaf.suffix=.html
|
访问结果如下

文章作者:阿文
版权声明:本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自
阿文的博客!