找到Thymeleaf配置文件
将Html页面放到classpath:/templates/
classpath:/templates/
Thymeleaf按照如下方式寻找资源和拼串儿
在html中取出值
1.页面中导入Thymeleaf名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2.利用 th:text 设置div的文本值
thymeleaf 众多属性
Thymeleaf基本表达式
Variable Expressions: ${…}
// 获取变量值 OGNL
- 获取对象属性,甚至调用方法
- 使用内置的基本对象:
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object
- 内置的工具对象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
Selection Variable Expressions: *{…}
用th:object 将 user 包装起来,后面的 * 表示该 object
Message Expressions: #{…}
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
Link URL Expressions: @{…}
注意这里是如何传递参数的
多个参数可以使用逗号分隔
Fragment Expressions: ~{…}
类似于引入命名空间内的方法或变量
其它表达式
literals字面值
追加文本
Arithmetic operations数学运算
Expression inlining 行内表达式
练习测试
- Controller
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "helloworld";
}
@RequestMapping("/test")
public String success(Map<String,Object> map){
map.put("hello","<h1>你好呀</h1>");
map.put("users", Arrays.asList("Tom","Jerry","Mickey"));
return "success";
}
}
- HTML
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Success</h1>
<div th:text="${hello}"></div>
<!-- utext 不转译 -->
<div th:utext="${hello}"></div>
<!-- th:each每次遍历都会生成这个标签 -->
<h4 th:each="user:${users}" th:text="${user}"></h4>
<hr/>
<h4>
<!-- 一个h4中包含多个span -->
<span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>