• 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.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </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,具体代码如下:

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <a href="/templates/index?lang=en_US">English(US)</a>
    <a href="/templates/index?lang=zh_CN">简体中文</a>
    <p><label th:text="#{message}"></label></p>
    </body>
    </html>
    

      

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

      

  • 相关阅读:
    如何利用U盘重装系统
    对于python爬虫urllib库的一些理解(抽空更新)
    由pthread库版本不一致导致的段错误
    使用WinDBG调试OnDO Server
    直接输出蛇形矩阵
    在Windows 7 x64 上编译libsvn
    Visual Studio Express 2012 安装缺少头文件、库文件的问题
    元和网络的密码加密过程
    有道网络查词的简单分析
    统一项目管理平台(UMPLatForm.NET)【开发实例】之产品管理(WinForm)
  • 原文地址:https://www.cnblogs.com/ooo0/p/16090177.html
Copyright © 2020-2023  润新知