Spring Boot 整合Thymeleaf

本文介绍了如何在Spring Boot项目中整合Thymeleaf模板引擎,用于处理HTML页面渲染。Thymeleaf是一个XML/XHTML/HTML5模板引擎,可替代JSP等其他模板引擎。文中详细讲解了Spring Boot默认的静态资源目录配置,以及如何添加Thymeleaf依赖,并配置application.properties。最后,通过编写Controller和index.html页面,展示了Thymeleaf的实际应用。
摘要由CSDN通过智能技术生成

我们使用Spring Boot的时候我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,我们可能会需要一些模板引擎,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 整合 Thymeleaf的步骤:

  1. 静态资源访问
    在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
    默认配置

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
2. 渲染web页面
在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供了默认配置的模板引擎主要有以下几种:
Thymeleaf
FreeMarker
Velocity
Groovy
Mustache
Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
在此我使用Thymeleaf
3. 引入添加thymeleaf依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 配置application.properties
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8

#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类里面有默认的配置。
spring-boot很多配置都有默认配置:
比如默认页面映射路径为classpath:/templates/*.html
同样静态文件路径为classpath:/static/

  1. 接下来我们就可以进行测试了,写一个Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafController {
    @RequestMapping("/thymeleaf")
    public String index(ModelMap map) {
        // 加入一个属性,用来在模板中读取
        map.addAttribute("baidu", "http://www.baidu.com");
        // return模板文件的名称,对应src/main/resources/templates/index.html
        System.out.println("hello world");
        return "index";
    }
}
  1. 编写 index.html
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1>Hello World</h1>
<h1 th:text="${baidu}" >Hello World</h1>
<a th:href="${baidu}">百度一下 你就知道</a>
</body>
</html>
  1. 访问,结果,点击链接能打开百度首页
    这里写图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值