Thymeleaf的标准表达式
标准变量表达式(${ })
语法:${ }
变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和JSTL中的${}
相同;
Thymeleaf中的变量表达式使用${变量名}
的方式和获取其中的数据
比如SpringMVC的Controller 中使用的model.addAttribute向前端传输数据,代码如下:
- 创建controller类
@Controller
public class UserController {
@RequestMapping("/user")
public String user(Model model) {
//先创建一个实体类,用于存放数据
User user = new User();
user.setId(1);
user.setName("张三");
user.setAge(14);
model.addAttribute("user", user);
return "user";
}
}
- 创建html页面前端接收代码
记得要在html标签中加入属性:xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<span th:text="${user.id}"></span>
<span th:text="${user.name}"></span>
<span th:text="${user.age}"></span>
</body>
</html>
其中,th:text=" "是Thymeleaf的一个属性,用于文本的显示;
3. 运行
选择变量表达式(*{ })
语法:*{ }
选择变量表达式,也叫星号表达式,使用th:object属性来绑定对象,比如:
- 和上面的Controller类一样
@Controller
public class UserController {
@RequestMapping("/user")
public String user(Model model) {
//先创建一个实体类,用于存放数据
User user = new User();
user.setId(1);
user.setName("张三");
user.setAge(14);
model.addAttribute(