一、标准表达式#{}
标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的 ${}相同。thymeleaf中的变量表达式使用${变量名}的方式获取Controller中 model其中的数据。
- Controller测试类
@Controller
public class UserController {
@RequestMapping("/user/detail")
public String userDetail(Model model) {
User user = new User();
user.setId(1);
user.setUsername("zac");
user.setAge(18);
model.addAttribute("user", user);
return "userDetail";
}
}
- 前端展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>标准变量表达式:#{} -> (推荐)</h1>
<div th:text="${user.id}"></div>
<div th:text="${user.username}"></div>
<div th:text="${user.age}"></div>
</body>
</html>
- 结果
二、选择变量表达式*{}
- 选择变量表达式展示上述结果
<h1>选择变量表达式(星号表达式):*{} -> (不推荐)</h1>
<!--
*{}必须使用th:object属性来绑定这个对象
-->
<div th:object="${user}">
<div th:text="*{id}"></div>
<div th:text="*{username}"></div>
<div th:text="*{age}"></div>
</div>
- 结果
<h1>标准变量表达式与选择变量表达式混合使用 -> (不推荐)</h1>
<div th:text="*{user.id}"></div>
<div th:text="*{user.username}"></div>
<div th:text="*{user.age}"></div>
三、路径表达式@{}
- Controller测试类
@RequestMapping("/url")
public String url(Model model) {
model.addAttribute("id", "1110");
model.addAttribute("username", "zac");
model.addAttribute("pwd", "123");
return "url";
}
@RequestMapping("/test")
@ResponseBody
public String test(String username) {
return "请求路径/test, 参数:" + username;
}
@RequestMapping("/test2")
@ResponseBody
public String test2(Integer id, String username, String pwd) {
return "请求路径/test2, 参数id=" + id + ",username=" + username +",pwd="+ pwd;
}
/**
* 测试RESTful风格
*/
@RequestMapping("/test3/{id}")
@ResponseBody
public String test3(@PathVariable("id") Integer id) {
return "请求路径/test3, 参数id=" + id;
}
- 展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>URL路径变量表达式</title>
</head>
<body>
<h1>url路径表达式:@{}</h1>
<h2>a标签中的绝对路径(无参数)</h2>
<a href="http://www.baidu.com">旧: 跳转到百度</a><br/>
<a th:href="@{http://www.baidu.com}">th: 跳转到百度</a><br/>
<a th:href="@{http://localhost:8080/user/detail}">跳转userDetail</a><br/>
<a href="http://localhost:8080/user/detail">跳转userDetail</a><br/>
<h2>相对表达式(无参数) -> (常用)</h2>
<a th:href="@{/user/detail}">跳转userDetail</a><br/>
<h2>绝对路径(带参数)</h2>
<a href="http://localhost:8080/test?username=zhangcan">绝对路径/test, 带username参数</a><br/>
<a th:href="@{http://localhost:8080/test?username=zhangcan}">路径表达式: 绝对路径/test, 带username参数</a><br/>
<h2>相对路径(带参数)</h2>
<a th:href="@{/test?username=zhangcan}">相对路径/test, 带username参数</a><br/>
<h2>相对路径获取后台参数值</h2>
<a th:href="@{'/test?username=' + ${id}}">相对路径获取后台参数值</a><br/>
<h2>相对路径(带多个参数) -> (推荐)</h2>
<a th:href="@{'/test2?id=' + ${id} + '&username=' + ${username} + '&pwd=' + ${pwd}}">1相对路径(带多个参数)</a><br/>
<a th:href="@{/test2(id=${id},username=${username},pwd=${pwd})}">2相对路径(带多个参数)</a><br/>
<a th:href="@{'/test3/' + ${id}}">测试RESTful风格</a><br/>
</body>
</html>
路径表达式除了适用于a标签,例如:导入图片路径、js、css等路径都使用,静态资源默认会在
/static/
下寻找