3 使用thymeleaf做页面模板(spring-boot 集成 thymeleaf)

要使用thymeleaf做页面模板,需要两步。

一、添加依赖

二、进行配置(需要定制化的时候就需要配置)

一、在pom.xml中添加如下代码:

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

    </dependency>

二、点击: Spring Boot Reference Guide

然后ctrl + F搜索 ,输入spring.thymeleaf.prefix,如下就是定位到的配置内容:


配置内容需要放在配置文件中,spring-boot默认的配置文件为 application.properties ,配置文件需要放在文件夹中,因此我们新建source folder


输入 src/main/resources ,完成之后,如下图


于是,在此文件夹下新建文件 application.properties,在其中填入如下代码:

spring.thymeleaf.cache=false # Enable template caching.
spring.thymeleaf.content-type=text/html # Content-Type value.
spring.thymeleaf.enabled=true # Enable MVC Thymeleaf view resolution.
spring.thymeleaf.encoding=UTF-8 # Template encoding.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.

spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.

现在先看一下包结构:


因此,在名为src/main/resources  的 sources folder 下新建名为 templates 的 folder,用来存放我们的页面模板,要注意,sources folder 和 folder 长得是不一样的,如下图:


在templates下新建文件hello.html,然后加入如下代码:


然后在DemoController.java类中加入如下代码:


然后启动应用,but,报错了,如下:


这是将hello.html中的修改为:

这只解决了一部分问题,是因为applicatin.properties文件中多了不需要的内容(后面的注释前面有个空格),删除多余的注释,如下:

spring.thymeleaf.cache=false
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.suffix=.html

然后,启动应用,访问 http://localhost:8080/demo/thymeleaf ,但是,还有错:


在定位console输出的异常信息:


故解决问题,在hello.html中添加代码: </meta> ,原来使用eclipse新建的html文件中默认是没有</meta>的。修改之后,再次访问,则访问成功.



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值