SpringBoot学习1.7-配置Thymeleaf渲染页面及常用标签说明

环境:

jdk1.8;spring boot2.0.2;Maven3.3

摘要说明:

前面我们已经主要讲述如何进行接口开发,接口开发之后如何进行页面渲染?
spring boot默认不支持jsp;主要支持下面渲染模版:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

本篇文章主要讲述如何配置使用Thymeleaf模版引擎进行页面渲染;

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

步骤:

1.依赖

引入依赖:

		<!-- 引入thymeleaf渲染模板 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

这里先阐述下Thymeleaf可以使用的mode如下:

  • XML
  • Valid XML
  • XHTML
  • Valid XHTML
  • HTML5(默认)
  • Legacy HTML5

由于除了Legacy HTML5之外,其他模式都必须是闭合的(标签),也就是说不支持不规范的HTML标签写法;

对于配置了Legacy HTML5模式的情况,Legacy HTML5先转换为规范写法的H5,so官方建议使用H5的代码来写模板;

这里说的使用Legacy HTML5需要另外引入依赖:

<dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
</dependency>

2.Thymeleaf配置

渲染页面首先需要放置静态页面;

Spring Boot默认提供静态资源目录位置需置于classpath下即放置在src/main/resources/下,目录名需符合如下规则:‘

  • /static
  • /public
  • /resources
  • /META-INF/resources

本篇文章使用常用的static;

Thymeleaf配置如下,主要指定前后缀及缓存:

#<!-- 关闭thymeleaf缓存 开发时使用 否则没有实时画面-->
spring.thymeleaf.cache=false
## 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template-location=true
#Content-Type值
spring.thymeleaf.content-type=text/html
#启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled=true
# 在构建URL时预先查看名称的前缀
spring.thymeleaf.prefix=classpath:/static/
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html
## 应该从解决方案中排除的视图名称的逗号分隔列表
#spring.thymeleaf.excluded-view-names=
#模板编码默认为html5
#spring.thymeleaf.mode=LEGACYHTML5
# 链中模板解析器的顺序
#spring.thymeleaf.template-resolver-order=o
# 可以解析的视图名称的逗号分隔列表
#spring.thymeleaf.view-names=

3.页面开发

静态资源开发结构如下:

两种方式访问页面;

一、直接访问页面,如http://127.0.0.1:xxxx/xx/test/html/test.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../js/jquery-1.11.2.js"></script>
<script>
	$(function() {
		$.ajax({
			async : false,
			type : "post",
			url : "../../swagger-resources/",
			data : null,
			dataType : 'json',
			success : function(data) {
				console.log(data);
			},
			error : function() {
				alert("请求服务超时");
			}
		});
	});
</script>
</head>
<body>
	<image src="../img/IMG_0143.JPG"></image>
</body>
</html>

二、通过controller进行跳转,同时使用Thymeleaf标签,如http://127.0.0.1:xxxx/xx/test1:

这里面注意的是使用@Controller注解而不是@RestController;因为后者默认返回json类型;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller//注意这里是@Controller而不是@RestController
public class TestThymeleafController {
    @RequestMapping("/test1")
    public String index(ModelMap map) {
        // 加入一个属性,用来在模板中读取
        map.addAttribute("host", "https://blog.csdn.net/u010904188/");
        // return模板文件的名称,对应src\main\resources\static\test\html\test1.html
        return "test/html/test1";
    }
}

静态页面如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1 th:text="${host}">Hello World</h1>
</body>
</html>

4.Thymeleaf常用标签

常用的标签有:

关键字功能介绍案例
th:id替换id<input th:id="'xxx' + ${collect.id}"/>
th:text文本替换<p th:text="${collect.description}">description</p>
th:utext支持html的文本替换<p th:utext="${htmlcontent}">conten</p>
th:object替换对象<div th:object="${session.user}">
th:value属性赋值<input th:value="${user.name}" />
th:with变量赋值运算<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style设置样式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick点击事件th:οnclick="'getCollect()'"
th:each属性赋值tr th:each="user,userStat:${users}">
th:if判断条件<a th:if="${userId == collect.userId}" >
th:unless和th:if判断相反<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href链接地址<a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch多路选择 配合th:case 使用<div th:switch="${user.role}">
th:caseth:switch的一个分支<p th:case="'admin'">User is an administrator</p>
th:fragment布局标签,定义一个代码片段,方便其它地方引用<div th:fragment="alert">
th:include布局标签,替换内容到引入的文件<head th:include="layout :: htmlhead" th:with="title='xx'"></head>
th:replace布局标签,替换整个标签到引入的文件<div th:replace="fragments/header :: title"></div>
th:selectedselected选择框选中th:selected="(${xxx.id} == ${configObj.dd})"
th:src图片类地址引入<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline定义js脚本可以使用变量<script type="text/javascript" th:inline="javascript">
th:action表单提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:attr设置标签属性,多个属性可以用逗号分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。

常用数据类型:

  • #dates:日期格式化内置对象,具体方法可以参照java.util.Date;
  • #calendars:类似于#dates,但是是java.util.Calendar类的方法;
  • #numbers: 数字格式化;
  • #strings:字符串格式化,具体方法可以参照java.lang.String,如startsWith、contains等;
  • #objects:参照java.lang.Object;
  • #bools:判断boolean类型的工具;
  • #arrays:数组操作的工具;
  • #lists:列表操作的工具,参照java.util.List;
  • #sets:Set操作工具,参照java.util.Set;
  • #maps:Map操作工具,参照java.util.Map;
  • #aggregates:操作数组或集合的工具;
  • #messages:操作消息的工具。

更多可参考:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#standard-expression-syntax

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Thymeleaf是一个流行的服务器端模板引擎,它可以将数据和模板相结合,生成HTML页面。而AJAX则是一种在不重新加载整个页面的情况下与服务器进行交互的技术。 在Spring Boot中集成Thymeleaf非常容易。首先,需要在pom.xml文件中添加Thymeleaf依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 接下来,可以创建一个Controller类来处理请求并返回HTML页面。例如: ```java @Controller public class MyController { @GetMapping("/") public String home(Model model) { model.addAttribute("message", "Hello Thymeleaf!"); return "index"; } } ``` 这个Controller类处理根路径的GET请求,并将一个名为“message”的属性添加到模型中。然后,它返回名为“index”的模板。 在这个例子中,“index”模板可以使用Thymeleaf标记来渲染页面。例如: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Page</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html> ``` 这个模板使用Thymeleaf语法来渲染一个标题,标题的文本来自于“message”模型属性。 现在,假设需要使用AJAX来从后端调用接口并渲染页面。可以使用jQuery库来简化这个过程。例如: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>My Page</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $.ajax({ url: "/api/data", success: function(data) { $("h1").text(data.message); } }); }); </script> </head> <body> <h1>Hello World!</h1> </body> </html> ``` 这个模板包含了一个名为“api/data”的接口调用,当页面加载时会自动调用该接口。当接口调用成功后,页面上的标题将被替换为返回的数据。注意,这里使用了jQuery的“$.ajax”函数来执行异步请求。 最后,需要在Controller中添加一个处理接口调用的方法。例如: ```java @RestController public class MyRestController { @GetMapping("/api/data") public Map<String, String> getData() { Map<String, String> data = new HashMap<>(); data.put("message", "Hello AJAX!"); return data; } } ``` 这个RestController类处理“api/data”路径的GET请求,并返回一个包含名为“message”的属性的Map对象。这个属性将被用于渲染页面标题。 如果一切正常,现在可以启动应用程序并访问根路径。页面将加载并显示一个标题“Hello World!”,然后自动使用AJAX调用接口“/api/data”,并将标题替换为返回的数据“Hello AJAX!”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值