Spring boot整合视图技术(Thymeleaf)

Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据产看显示效果。同时,Spring boot提供了Thymeleaf自动化配置解决方案,因此在Spring boot中使用Thymeleaf非常方便。Spring boot整合Thymeleaf步骤如下:
1、新建一个Spring boot项目,在pom.xml中添加依赖

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

2、配置Thymeleaf
Spring boot提供了Thymeleaf自动化配置类ThymeleafProperties

@Component
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
}

默认的模板位置在classpath:/templates/,默认的模板后缀为.html。
以下为开发者对默认的Thymeleaf配置参数进行自定义配置,在application.properties中进行配置,如下:

#是否开启缓存,开发时可设置为false,默认为true
spring.thymeleaf.cache=true

#检查模板是否存在,默认为true
spring.thymeleaf.check-template=true

#检查模板位置是否存在,默认为true
spring.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、配置实体类

public class BookEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String name;
    private String author;
    省略getter/setter
}

4、配置控制类

@RestController
public class BookController {
    @GetMapping("/books")
    public ModelAndView books() {
        List<BookEntity> books = new ArrayList<>();
        BookEntity b1 = new BookEntity();
        b1.setId(1);
        b1.setAuthor("罗贯中");
        b1.setName("三国演义");

        BookEntity b2 = new BookEntity();
        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;
    }
}

5、创建视图
在resources目录下的templates目录中创建books.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>
    <!--/*@thymesVar id="books" type="mapper"*/-->
    <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>

6、运行
在浏览器中访问地址http://localhost:8080/books
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值