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、测试

浙公网安备 33010602011771号