zoukankan      html  css  js  c++  java
  • Springboot 集成 Thymeleaf 及常见错误

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

    首先我们要在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 即可看到如下页面

    这就成功的集成了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中的一串字符
    3. 方法前不要加@ResponseBody,加这个注释相当于@RestController, 返回一串字符串同上
    4. 如果载application.properties重配置属性,一定要注意是否书写有误,不能多空格否则有可能会报如下错误:

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

      如有不当和错误之处,请指出,我们一起交流学习,共同进步!谢谢!

  • 相关阅读:
    SSM配置后可以访问静态html文件但无法访问其他后台接口的解决方案
    使用Idea部署SSM项目后,访问路径为url:8080/项目名_war_exploded的解决方案
    gym102302E_Chi's performance
    Linux命令之wc(Word Count)
    【贪心算法】最大整数
    贪心算法讲解及例题
    【贪心算法】均分纸牌
    【贪心算法】背包问题
    【基础题】字符串替换
    【基础题】对称排序
  • 原文地址:https://www.cnblogs.com/zhang-dongliang/p/10968878.html
Copyright © 2011-2022 走看看