springboot 整合Thymeleaf


Thymeleaf是新一代Java模板引擎,类似于Velocity、FreeMarker等传统Java模板引擎。与传统Java模板引擎不同的是,Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果。同时,Spring Boot提供了Thymeleaf自动化配置解决方案

添加依赖

添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

配置Thymeleaf

Spring Boot为Thymeleaf提供了自动化配置类ThymeleafAutoConfiguration,相关的配置属性在ThymeleafProperties类中

如果开发者想对默认的Thymeleaf配置参数进行自定义配置,那么可以直接在application.properties中进行配置,部分常见配置如下:

spring:
  thymeleaf:
    cache: false # thymeleaf缓存是否开启 开发时建议关闭 否则更改页面后不会实时展示效果
    encoding: UTF-8 # thymeleaf编码格式
#    mode: LEGACYHTML5 # thymeleaf对html校验很严格,用这个去除thymeleaf严格校验
    prefix: classpath:/templates/ # thymeleaf模板文件前缀
    suffix: .html # thymeleaf模板文件后缀

配置控制器

    @GetMapping("/templates/index")
    public ModelAndView index() {
        Locale locale = LocaleContextHolder.getLocale();

        ModelAndView mv = new ModelAndView();
        mv.addObject("message", messageSource.getMessage("message", null, locale));
        mv.setViewName("index");
        return mv;
    }

创建视图

在resources目录下的templates目录中创建index.html,具体代码如下:




    
    Title


English(US)
简体中文

关于Thymeleaf的更多资料,可以查看https://www.thymeleaf.org。