目录
1. Thymeleaf 是什么?
2. 为什么要使用Thymeleaf?
3. 使用Thymeleaf
3.1 jar包依赖
3.2 在application.properties中配置thymleaf
4. Thymeleaf语法与案例操作
4.1 源码分析
4.2 案例
4.2.1 th属性
4.2.2 实操
Spring Boot 【模板引擎】thymeleaf
简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。
从代码层次上讲:Thymeleaf是一个java类库,他是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。
使用jsp的弊端
Thymeleaf的优点
注意:Spring-boot支持FreeMarker、Thymeleaf、jsp、veocity 。但是对freemarker和thymeleaf的支持最好,不推荐使用jsp
org.springframework.boot
spring-boot-starter-thymeleaf
# thymeleaf:
# #前缀
# prefix: classpath:/templates/
# #后缀
# suffix: .html
# # 模板格式
# mode: HTML5
# encoding: UTF-8
# servlet:
# content-type: text/html
# cache: false
# check-template-location: true
spring.thymeleaf.mode = LEGACYHTML5
这个配置不是必须的,但是spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。
查看部分源码如下
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
//规则前缀
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//规则后缀
public static final String DEFAULT_SUFFIX = ".html";
...
}
查看以上源码,thymeleaf的自动配置了规则前缀和后缀,所以只要我们把html页面放在calsspath:/templates/下,thymeleaf就能自动渲染。
html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。
使用Thymeleaf属性需要注意点以下五点:
如果在页面引用表达式变量报红色警告的就把下列代码引入该页面头部
package com.jmh.springthymeleaf.conyroller;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 蒋明辉
* @data 2022/11/15 8:41
*/
@Controller
public class IndexConytroller {
@Data
@AllArgsConstructor
@NoArgsConstructor
class Dog{
String id;
String name;
String sex;
int age;
}
@RequestMapping("/")
public ModelAndView index(){
//实例对象modelAndView
ModelAndView modelAndView=new ModelAndView();
//1.将字符串保存到作用域里面
modelAndView.addObject("name","蒋明辉");
modelAndView.addObject("uname","蒋明辉是个大帅比");
//2.将对象保存到作用域里面
modelAndView.addObject("dog",new Dog("1","旺财","公",8));
//3.将对象集合保存到作用域里面
List dogs=new ArrayList<>();
dogs.add(new Dog("1","旺财","公",18));
dogs.add(new Dog("2","来福","公",28));
dogs.add(new Dog("3","许杰","母",38));
modelAndView.addObject("dogs",dogs);
//4.将map集合保存到作用域里面
Map map=new HashMap<>();
map.put("Boss",new Dog("1","旺财","公",8));
modelAndView.addObject("map",map);
//5.绑定一个字符串
modelAndView.addObject("itdragonStr","this is a DEMO");
//跳转视图
modelAndView.setViewName("index");
return modelAndView;
}
}
首页
springboot整合thymeleaf模板引擎
姓名:
年龄:
性别:
编号
姓名
年龄
性别
操作
删除/修改
...
#strings
Old Str :
toUpperCase :
toLowerCase :
equals :
equalsIgnoreCase :
indexOf :
substring :
replace :
startsWith :
contains :
...