《SpringBoot+Vue》Chapter03 整合视图层

Thymeleaf

Thymeleaf是新一代Java模板引擎,与传统Java模板引擎不同的是,Thymeleaf支持HTML原型,可以让前端工程师直接在浏览器中打开查看样式,也可以让后端工程师结合真实数据查看显示效果。SpringBoot提供了Thymeleaf自动化配置解决方案。

创建工程,添加依赖

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

配置Thymeleaf

SpringBoot为Thymeleaf提供了自动化配置类ThymeleafAutoConfiguration,相关的配置属性在ThymeleafProperties类中

  • 默认的模板位置在:classpath:/templates/
  • 默认的模板后缀为:.html
    如果开发者想修改默认的配置,则可以直接在application.properties中进行配置
# 配置Thymeleaf
# 开启模板缓存
spring.thymeleaf.cache=true
# 检查模板是否存在
spring.thymeleaf.check-template=true
# 模板文件编码
spring.thymeleaf.encoding=utf-8
# 模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
# content-type配置
spring.thymeleaf.servlet.content-type=text/html
# 模板文件后缀
spring.thymeleaf.suffix=.html

配置控制器

创建Book实体类,Controller中返回ModelAndView

@Controller
public class BookController {
    @GetMapping("/books")
    public ModelAndView books() {
        ArrayList<Book> books = new ArrayList<Book>();
        for (int i = 0; i < 3; i++) {

            Book book = new Book(i, "book" + i, "author" + i);
            books.add(book);
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("books", books);
        mv.setViewName("books");
        return mv;
    }
}

创建视图

在resources目录下的templates目录中创建books.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>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 th:text="${book.name}"/>
        <td th:text="${book.author}"/>
    </tr>

</table>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容