springboot2—thymeleaf

介绍

教程
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html

准备工作

pom.xml

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

application.yml

spring:
  thymeleaf:
    prefix: classpath:/templates/   #模版路径
    suffix: .html                   #模版后缀
    servlet:
      content-type: text/html       #设置 Content-type
    encoding: UTF-8                 #编码方式
    mode: HTML5                     #校验 H5 格式
    cache: false                    #关闭缓存,在开发过程中可以立即看到页面修改的结果

页面
xxx.html
需要引⼊模版标签。
<html xmlns:th="http://www.thymeleaf.org">
2、通过特定的标签完成操作。
<p th:text="${name}">Hello World</p>
Thymeleaf 模版标签不同于 JSTL,Thymeleaf 模版标签是直接嵌⼊到 HTML 原⽣标签内部。

后端发送请求的方式

  • 在URL的请求路径中增添参数
  • 使用url+参数的方式完成数据的请求
  • 使用ajax
  • 使用form的方法

比较

我们对上面的几种方法进行比较

方法形式优势
url路由带参数/student/{id}简单、便捷
url+参数@{href="{/student/(value=${object.x})}"}可以简单实现多参数的传递
ajax$(‘ajax’){…}可以传递多种复杂的数据类型
form<form action="{target}" type=""> …</form>可以直接将填写的数据发送

实现

url路由带参数

<a href="#" th:href="@{/admin/news/{id}/toUpdate(id=${news.id})}" class="ui mini teal basic button">编辑</a>

url+参数

<a href="#" th:href="@{/student/chooseClassLogic(studentId=${course.studentId},courseId=${course.courseId},startTime=${course.startTime},endTime=${course.endTime})}" class="ui positive button">添加</a>

ajax方式

$.ajax({
    type : 'post',
    url: "/student/changePassword",
    data:  {repassword, password},
    success: function (res) {
        alert(res.message)
        $(location).attr('href', '/student/profile')
    },
    error: function (err) {
        alert('更新用户失败')
    }
})

form表单

<form action="/student/loginJudge" method="get">
    <input type="text" value="" placeholder="用户名" name="name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'User name';}"/>
    <input type="password" value="" placeholder="密码" name="password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'password';}"/>
    <div class="remember">
	<span class="checkbox1">
	<label class="checkbox"><input type="checkbox" name="" checked=""><i> </i>记住我 </label>
	</span>
       <div class="forgot">
           <h6><a href="#">忘记密码</a></h6>
       </div>
       <div class="clear"></div>
    </div>
    <input type="submit" value="Login">
</form>

常用标签

迭代

<tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<table>
	<tr>
		<th>编号</th>
		<th>姓名</th>
	</tr>
	<tr th:each="user:${list}">
		<td th:text="${user.id}"></td>
		<td th:text="${user.name}"></td>
	</tr>
</table>

表单

<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}"

隐藏的标签

<th:block></th:block>是Thymeleaf提供的唯一的一个Thymeleaf块级元素,其特殊性在于Thymeleaf模板引擎在处理<th:block>的时候会删掉它本身,标签本身不显示,而保留其内容

可以跟if 和foreach结合

th:text

th:text ⽤于⽂本的显示,将业务数据的值填充到 HTML 标签中。

th:if

th:if ⽤于条件判断,对业务数据的值进⾏判断,如果条件成⽴,则显示内容,否则不显示,具体的使⽤
如下所示。

@GetMapping("/if")
public ModelAndView ifTest(){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("test");
	modelAndView.addObject("score",90);
	return modelAndView;
}
<p th:if="${score>=90}">优秀</p>
<p th:if="${score<90}">良好</p>

th:unless

th:unless 也⽤作条件判断,逻辑与 th:if 恰好相反,如果条件不成⽴则显示,否则不显示。

<p th:unless="${score>=90}">优秀</p>
<p th:unless="${score<90}">良好</p>

th:switch th:case

th:switch th:case 两个结合起来使⽤,⽤作多条件等值判断,逻辑与 Java 中的 switch-case ⼀致,当switch 中的业务数据等于某个 case 时,就显示该 case 对应的内容。

<div th:switch="${studentId}">
<p th:case="1">张三</p>
<p th:case="2">李四</p>
<p th:case="3">王五</p>
</div>

th:action

⽤来指定请求的 URL,相当于 form 表单中的 action 属性

<form th:action="@{/hello/login}" method="post">
<input type="submit"/>
</form>

th:value

⽤来给标签赋值。

<input type="text" th:value="${value}"/>

th:src

⽤来引⼊静态资源,相当于 HTML 原⽣标签 img、script 的 src 属性。
图⽚,css,js,静态加载的 html 都需要放置在 resources/static ⽂件中

@GetMapping("/src")
	public ModelAndView src(){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("test");
	modelAndView.addObject("src","/1.png");
	return modelAndView;
}
<img th:src="${src}"/>

如果 src 的值直接写在 HTML 中

<img th:src="@{/1.png}"/>

th:selected

⽤作给 HTML 元素设置选中,条件成⽴则选中,否则不选中。

@GetMapping("/select")
	public ModelAndView select(){
	List<User> list = Arrays.asList(
		new User(1,"张三"),
		new User(2,"李四"),
		new User(3,"王五")
	);
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("test");
	modelAndView.addObject("list",list);
	modelAndView.addObject("name","李四");
	return modelAndView;
}
<select>
	<option
		th:each="user:${list}"
		th:value="${user.id}"
		th:text="${user.name}"
		th:selected="${user.name == name}"
	></option>
</select>

结合 th:each 来使⽤,⾸先遍历 list 集合动态创建 option 元素,根据每次遍历出的 user.name 与业务数据中的 name 是否相等来决定是否要选择。

设置属性

一个值

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>

多个值

<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
@GetMapping("/attr")
public ModelAndView attr(){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("test");
	modelAndView.addObject("attr","Spring Boot");
	return modelAndView;
}
<input th:attr="value=${attr}"/><br/>
<input th:value="${attr}"/>

Thymeleaf 内置对象

  • dates:⽇期格式化
  • calendars:⽇期操作
  • numbers:数字格式化
  • strings:字符串格式化
  • bools:boolean
  • arrays:数组内置对象
  • lists:List 集合内置对象
  • sets:Set 集合内置对象
  • maps:Map 集合内置对象
@GetMapping("/utility")
public ModelAndView utility(){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("test");
	modelAndView.addObject("date",new Date());
	Calendar calendar = Calendar.getInstance();
	calendar.set(2020,1,1);
	
	modelAndView.addObject("calendar",calendar);
	modelAndView.addObject("number",0.06);
	modelAndView.addObject("string","Spring Boot");
	modelAndView.addObject("boolean",true);
	modelAndView.addObject("array",Arrays.asList("张三","李四","王五"));
	
	List<User> list = new ArrayList<>();
	list.add(new User(1,"张三"));
	list.add(new User(2,"李四"));
	modelAndView.addObject("list",list);
	
	Set<User> set = new HashSet<>();
	set.add(new User(1,"张三"));
	set.add(new User(2,"李四"));
	modelAndView.addObject("set",set);
	
	Map<Integer,User> map = new HashMap<>();
	map.put(1,new User(1,"张三"));
	map.put(2,new User(2,"李四"));
	modelAndView.addObject("map",map);
	return modelAndView;
}
date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span><br/>
当前⽇期:<span th:text="${#dates.createToday()}"></span><br/>
当前时间:<span th:text="${#dates.createNow()}"></span><br/>
Calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}">
</span><br/>
number百分⽐格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span>
<br/>
name是否为空:<span th:text="${#strings.isEmpty(string)}"></span><br/>
name⻓度:<span th:text="${#strings.length(string)}"></span><br/>
name拼接:<span th:text="${#strings.concat('Good',string)}"></span><br/>
boolean是否为true:<span th:text="${#bools.isTrue(boolean)}"></span><br/>
arrays的⻓度:<span th:text="${#arrays.length(array)}"></span><br/>
arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span>
<br/>
List是否为空:<span th:text="${#lists.isEmpty(list)}"></span><br/>
List的⻓度:<span th:text="${#lists.size(list)}"></span><br/>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: springboot+thymeleaf项目是一种基于Java语言开发的Web应用程序。它采用了Spring Boot框架和Thymeleaf模板引擎,可以快速地搭建一个高效、可靠、易于维护的Web应用程序。该项目具有以下特点: 1. 简单易用:Spring Boot框架提供了一系列的自动化配置,使得开发者可以快速地搭建一个Web应用程序,而不需要过多的配置。 2. 高效可靠:Spring Boot框架采用了一系列的优化措施,使得应用程序具有高效、可靠的性能。 3. 易于维护:Thymeleaf模板引擎提供了一种简单、易于维护的模板语言,使得开发者可以快速地开发出具有良好可读性的Web应用程序。 总之,springboot+thymeleaf项目是一种非常优秀的Web应用程序开发框架,可以帮助开发者快速地开发出高效、可靠、易于维护的Web应用程序。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发框架,这个框架的优点在于其简单易用,能够快速搭建一个Java Web应用程序,无需进行复杂的配置和繁琐的XML文件编写。而Thymeleaf则是一种Web和HTML的模板引擎,可以方便地处理文本、链接和表单等元素,支持多重继承和页面片段的复用等特性。 Spring Boot和Thymeleaf的结合,可以帮助开发人员更加简便地搭建Web应用程序。在使用Spring Boot进行项目开发时,可以使用Thymeleaf来完成Web开发的视图层,进行模版板的渲染和数据绑定。这样就可以很直接地将数据通过模板引擎展现出来,且更加方便。 在一个Spring Boot Thymeleaf项目的构建中,需要进行如下步骤: 1. 首先,引入Spring Boot和Thymeleaf的依赖以及其他必要的依赖,例如web和mybatis等相关组件。 2. 创建一个Controller类,并使用@Controller注解将类标记为Controller,编写具体的Action方法,这些方法可以用@RequestMapping或@GetMapping等注解来定义处理请求的URL路径和请求类型等相关信息。 3. 创建一个Model类,用于封装需要传输到前端的数据和相关操作等。 4. 在Controller内部设置Model变量并将相关数据注入Model,然后将需要展现的数据作为参数传递给Thymeleaf进行渲染,最后将渲染完成后的结果返回给前端页面展现。 5. 编写HTML页面,使用Thymeleaf标签来渲染动态数据。 需要注意的是,在进行Thymeleaf模板的渲染时,需要遵守一定的规范,例如页面中的数据变量名称需与Model中的属性名称一致,引入Thymeleaf命名空间等等。 总之,Spring Boot与Thymeleaf结合使用可以帮助开发人员快速地完成Web开发,整个过程简单而且高效。使用Thymeleaf能够降低模版制作的门槛,进一步提高开发效率,并且能够提供丰富的模版处理标签,使得页面制作更加灵活。 ### 回答3: 近年来,使用SpringBootThymeleaf进行Web开发已经成为越来越多的开发者选择的方案。SpringBoot是一个基于Spring框架的快速Web应用开发框架,而Thymeleaf是一种基于HTML的模板引擎,其中需要了解的内容包括以下几点: 首先,SpringBoot框架的优点是非常明显的。它提供了很多便于使用的方法,例如自动装配,以及基于配置的许多默认值。这使得开发者可以花更少的时间和精力来开发项目,将重点放在业务逻辑和功能实现上。 其次,Thymeleaf是一种非常强大和灵活的模板引擎,其语法简单易懂,而且支持HTML5标准。它还提供了一些样式和布局的工具,以及易于使用的表达式和标签,使得Web页面开发更加容易。 当然,SpringBoot集成Thymeleaf的过程也并不复杂。只需添加thymeleaf-starter包依赖,SpringBoot将自动将Thymeleaf注册为默认的模板引擎。然后,您只需要编写Thymeleaf模板文件即可。 最后,值得注意的是,使用SpringBootThymeleaf进行Web开发的好处在于它们之间的紧密集成。这种紧密集成可以更轻松地创建动态和交互性的Web应用程序,这是传统的HTML和JavaScript不能提供的。 总的来说,SpringBootThymeleaf是一对非常强大且易于使用的Web开发工具组合,它们的出现大大提高了Web开发的效率和质量,同时也为开发人员提供了更好的开发体验。我们相信,这对于Web开发者来说是非常有价值的组合。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值