Springboot 集成 Thymeleaf 及常见错误

Thymeleaf模板引擎是springboot中默认配置,与freemarker相似,可以完全取代jsp,在springboot中,它的默认路径是src/main/resources/templates 静态文件css, js 等文件默认路径是src/main/resources/static,所有项目中如果没有这个目录需要手动加上了

16535373-023b53dbc379db27.png

首先我们要在pom.xml文件中添加依赖

<!-- thymeleaf 模板引用  -->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>  </dependency>

引用之后我们就来测试一下, 在pom.xml中引入依赖之后。你完全可以不用配置(也秉承了springboot 约定优于配置)当然你如果需要自定义一些属性,你可以在application.properties 中添加配置。

测试类@Controller

/**
 * @author pillarzhang
 * @date 2019-06-03
 */
@Controller
public class loginController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

Index,html 页面如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<p style="color:red">hello world</p>
</body>
</html>

启动项目,输入http://localhost:8081/index 即可看到如下页面

16535373-1daa4ad587c3270d.png

这就成功的集成了Thymeleaf。

注意:前面也说了,如果你不配置任何属性依然可以使用,当然你也可以自己设置,在配置文件中application.properties 设置相应的属性

spring.thymeleaf.prefix=classpath:/templates/  设置thymeleaf路径默认为src/main/resources/templates
spring.thymeleaf.suffix=.html  设置thymeleaf模板后缀
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false  是否开启缓存默认为true
spring.thymeleaf.mode=LEGACYHTML5  设置thymeleaf严格校验
spring.thymeleaf.encoding=UTF-8    设置编码
  1. 配置完成之后一定要注意路径地址是否正确,

  2. 一定要用@Controller,如果使用@RestController,有可能返回return中的一串字符


    16535373-ca68f294c2e824b0.png
  3. 方法前不要加@ResponseBody,加这个注释相当于@RestController, 返回一串字符串同上

  4. 如果载application.properties重配置属性,一定要注意是否书写有误,不能多空格否则有可能会报如下错误:


    16535373-4203426b138ad692.png

至此,springboot集成thymeleaf 就完成了,虽然中间遇到了一些小问题,还好解决了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值