美文网首页读书笔记——SpringBoot+Vue开发实战
《SpringBoot+Vue》Chapter03 整合视图层

《SpringBoot+Vue》Chapter03 整合视图层

作者: So_ProbuING | 来源:发表于2023-12-04 08:42 被阅读0次

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>

相关文章

网友评论

    本文标题:《SpringBoot+Vue》Chapter03 整合视图层

    本文链接:https://www.haomeiwen.com/subject/uszkgdtx.html