Spring Boot配置Thymeleaf模版引擎

1 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(文档对象模型)上执行预先制定好的逻辑。

2 文件目录

3 thymeleaf依赖 

pom.xml导入thymeleaf依赖 。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

4 application.properties

application.properties加入thymeleaf配置。

# 后缀
spring.thymeleaf.prefix=classpath:/templates/
# 模板格式
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.suffix=.html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

5 新建页面跳转PageController类

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
    //页面跳转
    @RequestMapping("/{page}")
    public String page(@PathVariable("page") String page) {
        return page;
    }
    //首页跳转
    @RequestMapping("/index")
    public String index2() {
        return "index";
    }
    @RequestMapping("/")
    public String index(){
        return "index";
    }
}

6 templates文件夹下添加index.html文件

7 index.html内容

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>旭东怪</title>
    <link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}"/>
</head>
<body>
欢迎来到旭东怪的主页!
</body>
</html>

8 地址栏调试

9 可能出现的问题

请参考以下博客:

Thymeleaf Error resolving template [index],template might not exist or might not be accessible问题解决

Thymeleaf Error resolving template [favicon.ico], template might not exist问题解决

Thymeleaf 修改页面内容之后实时生效两种方法(热部署,手动编译)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值