随笔 - 303  文章 - 0  评论 - 3  阅读 - 15万

Spring Boot Web开发之Thymeleaf模板引擎

  Spring MVC 九大组件及其配置总结中关于九大组件的功能有了简单地介绍,同时也简单提及模板引擎与Spring MVC的集成。下面以Thymeleaf与Spring MVC集成为例,其在Spring Boot中如何进行集成的:

  Thymeleaf已经提供了ThymeleafView(默认)和ThymeleafViewResolver,同时其亦提供了一个SpringTemplateEngine类用来驱动在Spring MVC下使用Thymeleaf模板引擎及TemplateResolver用来设置通用的模板引擎——这使得在Spring MVC中集成Thymeleaf引擎变得简单:

          

   在Spring Boot中以上操作都不需要,其通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置

          

  下面详细研究下这几个类:

    通过ThymeleafAutoConfiguration类对集成所需要的Bean进行自动配置,包括templateResolver、templateEngine和thymeleafViewResolver的配置:

          

    通过ThymeleafProperties来配置Thymeleaf,在application.properties中以spring.thymeleaf开头来配置其用户自适应属性:

          

   Spring Boot自动配置Thymeleaf引擎实战,如下:

    1、静态页面

          

    2、Controller

          

       注意此控制器一定要使用@Controller,而不是@RestController,或者方法上有注解@ResponseBody。因为如果使用导致返回的不是指定的渲染页面而是字符串。

    3、application.yml

            

      为什么将静态页面目录再次复现呢?因为yml配置中路径与其息息相关,稍有差池就会提示500的错误。同时需要注意静态页面一定要放在resources下,且Spring Boot支持的静态资源目录可以是:

          

      classpath:后的起始“/”即最后的“/”不能缺失。

    4、测试

          

 

 

 

  

posted on   池塘里洗澡的鸭子  阅读(234)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示