暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SpringBoot详细教程 | 第十六篇:Spring Boot整合Thymeleaf模板引擎开发Web应用

小东IT技术分享 2019-03-08
311


Spring Boot提供了大量的模板引擎,包含了FreeMarker,Groovy,Thymeleaf,Velocity和Mustache,Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。

一. Thymeleaf简介

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

二. Spring Boot静态资源路径

创建一个Spring Boot项目标准的结构应该为



resources下

static静态资源路径 js/css等

templates 模板配置路径 html/ftl

三. 整合

在Spring Boot中使用Thymeleaf,只需要引入依赖,以及在配置文件application进行配置并在默认的模板路径src/main/resources/templates下编写模板文件即可完成

引入依赖

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>

  4. </dependency>

application.properties

  1. # 默认路径

  2. spring.thymeleaf.prefix=classpath:/templates/

  3. # 后缀

  4. spring.thymeleaf.suffix=.html

  5. # 模板格式

  6. spring.thymeleaf.mode=HTML5

  7. # 字符编码

  8. spring.thymeleaf.encoding=UTF-8

  9. # 内容格式

  10. spring.thymeleaf.servlet.content-type=text/html

  11. # 是否打开缓存 一般在开发过程中不建议打开

  12. spring.thymeleaf.cache=false

在完成配置之后,在快速入门工程的基础上,举一个简单的示例来通过Thymeleaf渲染一个页面

  1. package com.li.springbootthymeleaf;


  2. import org.springframework.boot.SpringApplication;

  3. import org.springframework.boot.autoconfigure.SpringBootApplication;

  4. import org.springframework.ui.ModelMap;

  5. import org.springframework.web.bind.annotation.RequestMapping;


  6. @SpringBootApplication

  7. public class SpringbootThymeleafApplication {


  8. public static void main(String[] args) {

  9. SpringApplication.run(SpringbootThymeleafApplication.class, args);

  10. }



  11. @RequestMapping("/index")

  12. public String index(ModelMap modelMap){

  13. // 加入一个属性,模板通过这个属性读取对应的值

  14. modelMap.addAttribute("host","www.lhdyx.cn");

  15. // return模板文件的名称,对应src/main/resources/templates/hello.html

  16. return "hello";

  17. }

  18. }

hello.html

  1. <!DOCTYPE html>

  2. <html lang="en">

  3. <html xmlns:th="http://www.thymeleaf.org">

  4. <head>

  5. <meta charset="UTF-8">

  6. <title>我的博客</title>

  7. </head>

  8. <body>


  9. <h1 th:text="${host}">我的博客地址</h1>

  10. </body>

  11. </html>

如上页面,直接打开html页面展现我的博客,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:https://www.lhdyx.cn



更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。

有的人比较喜欢写JSP进行开发页面,官方不建议使用,我个人也是不建议的,但如果一定要使用,我下篇文章介绍

源码下载:https://github.com/LiHaodong888/SpringBootLearn


文章转载自小东IT技术分享,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论