Springboot 集成 Thymeleaf 及常见错误

  Thymeleaf模板引擎是springboot中默认配置,与freemarker类似,能够彻底取代jsp,在springboot中,它的默认路径是src/main/resources/templates    静态文件css, js 等文件默认路径是src/main/resources/static,全部项目中若是没有这个目录须要手动加上了css

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

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

  

引用以后咱们就来测试一下, 在pom.xml中引入依赖以后。你彻底能够不用配置(也秉承了springboot 约定优于配置)固然你若是须要自定义一些属性,你能够在application.properties 中添加配置。java

测试类@Controllerspring

/**
 * @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 便可看到以下页面springboot

这就成功的集成了Thymeleaf。app

 

注意:前面也说了,若是你不配置任何属性依然可使用,固然你也能够本身设置,在配置文件中application.properties 设置相应的属性jsp

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中的一串字符
  3. 方法前不要加@ResponseBody,加这个注释至关于@RestController, 返回一串字符串同上
  4. 若是载application.properties重配置属性,必定要注意是否书写有误,不能多空格不然有可能会报以下错误:

     

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

 

  若有不当和错误之处,请指出,咱们一块儿交流学习,共同进步!谢谢!学习

相关文章
相关标签/搜索