学习SpringBoot集成(五)—Thymeleaf篇

学习SpringBoot集成(五)—Thymeleaf篇Thymeleaf是什么? 继上一次SpringBoot集成MyBatis之后,本篇文章主要讲解SpringBoot在web端的开发。Sprin

大家好,欢迎来到IT知识分享网。

Thymeleaf是什么?

继上一次SpringBoot集成MyBatis之后,本篇文章主要讲解SpringBoot在web端的开发。SpringBoot提供了大量模板引擎的支持,如FreeMarker、Groovy、Thymeleaf、Velocity和Mustache等。Spring Boot推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。

Thymeleaf的集成

通过Gradle工具,从Maven仓库中自动拉取如下几个文件:

compile ‘org.springframework.boot:spring-boot-starter-thymeleaf’

在Spring Boot中集成Thymeleaf,不像SpringMVC中那么繁琐,Spring Boot通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动化配置。

Thymeleaf的配置

集成好Thymeleaf所需要的jar包后,需要在Application.properties文件中进行配置。配置内容如下:

spring.thymeleaf.contentType 模板的媒体类型设置,默认为“text/html”

spring.thymeleaf.encoding 模板的编码设置,默认为“UTF-8”

spring.thymeleaf.mode 模板模式设置,默认为HTML5

spring.thymeleaf.prefix 前缀设置,默认为是“classpath:/templates/”

spring.thymeleaf.suffix 后缀设置,默认为“.html”

spring.thymeleaf.cache 模板缓存,默认为打开

备注:开发阶段,建议把模板缓存关闭,减少调试等待的时间

Thymeleaf的开发

在当前工程的resource目录下,新增文件夹templates,手动创建一个页面,index.html。html文件的头部,需要引入thymeleaf独有的命名空间。如果需要引入js、css、images等资源,Thymeleaf默认读取的是resources下的static目录。如下所示:


学习SpringBoot集成(五)---Thymeleaf篇

静态资源存放的目录位置

<!DOCTYPE html>

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

<head th:fragment=”head”>

<meta charset=”UTF-8″/>

<meta name=”viewport” content=”width=device-width, initial-scale=1″/>

<title th:text=”Test”>Test</title>

</head>

<body>

<span th:text=”${hello}”></span>

</body>

</html>

在上面的代码中,请读者注意,小编定义了一个th:text的span标签。通过Controller层跳转index.html页面时,模板引擎会自动扫描页面中的th标签,自动将标签对应的数据进行注入。除了th:text标签外,Thymeleaf还有很多其他的标签,例如:th:if、th:each、th:src等等。

在Controller层定义时,需要把返回的数据,存放入Map中。代码如下:

@Controller

public class TestController {

@RequestMapping(“/test”)

public String test(Map<String,Object> map){

map.put(“hello”,”Hello World!”);

return “test”;

}

}

启动工程以后,访问http://localhost:port/test ,页面自动打出了Hello World! 代表模板正常访问成功。

(完)

下一篇章:Tomcat日志集成log4j

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/50889.html

(0)
上一篇 2024-08-20 17:15
下一篇 2024-08-22 19:45

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信