SpringBoot自学好几天 中途开始写笔记 SpringBoot Web开发 thymeleaf 引入 20190120
SpringBoot
默认是以jar包方式+嵌入式tomcat形式发布 不支持jsp
所以我们要使用thymeleaf模板引擎来写我们的代码
模板引擎
JSP Velocty FreeMarker thymeleaf
各种模板引擎的基本思想是一样的,就是通过引擎把数据映射到静态的模板里边,然后展示给用户
SpringBoot推荐使用Thymeleaf :
语法简单 功能强大
1. 引入Thymeleaf
<!--2.0版本之前 如果想用新版本的thymeleaf 需要加入这个properties 它就是覆盖了parent依赖里边配置的内容 -- 但是之后版本默认的使用thymeleaf都是3以上了 -->
<properties>
<!--thymeleaf3主程序-->
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!--thymeleaf 布局功能支持程序 如果是thymeleaf3 适配 layout 2以上版本-->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
<!--引入thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1. Thymeleaf 使用和语法
@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";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
//默认前缀 只要我们把html页面放到这个文件夹下 thymeleaf就能帮我们渲染了
private String prefix = "classpath:/templates/";
//默认后缀
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
private boolean cache;
private Integer templateResolverOrder;
private String[] viewNames;
private String[] excludedViewNames;
private boolean enableSpringElCompiler;
private boolean renderHiddenMarkersBeforeCheckboxes;
private boolean enabled;
private final ThymeleafProperties.Servlet servlet;
private final ThymeleafProperties.Reactive reactive;
@RequestMapping("/succ")
public String succ(){
//会去找 classpath:/templates/succ.html
return "succ";
}
使用:
1)导入thymeleaf的名称空间(页面可以提示)
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2)使用thymeleaf的语法
@RequestMapping("/succ")
public String succ(Map<String,String> map){
map.put("hello","激动啊");
//会去找 classpath:/templates/succ.html
return "succ";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<!--th:text 将div的值设置为指定值-->
<div th:text="${hello}"></div>
</body>
</html>
语法规则:
- tx:text 改变当前元素里面的文本内容
- th:任意html属性 ; 替换原生属性的值
@RequestMapping("/succ")
public String succ(Map<String,String> map){
map.put("hello","激动啊");
map.put("id","testid");
map.put("class","testclass");
//会去找 classpath:/templates/succ.html
return "succ";
}
<div th:id="${id}" th:class="${class}" th:text="${hello}"></div>
3)能写哪些表达式? 参考下载的pdf第四张Standard Expression Synt
Simple expressions:(表达式语法)
Variable Expressions: ${...} 获取变量值 OGNL
1)获取对象属性、调用方法
2)使用内置的基本对象
#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.
例子:th:text="${#locale.country}">
3)内置的工具对象
#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
Page 20 of 106
#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一起使用 用*代替已经获取的值对象
Message Expressions: #{...}
获取国际化内容
Link URL Expressions: @{...}
定义url链接
原来:'http://localhost:8080/gtvg/order/details?orderId=3'
现在:
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}"
th:href="@{/order/details(orderId=${o.id})}"
th:href="@{/order/{orderId}/details(orderId=${o.id})}"
多个参数:@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}
片段引用表达式
<div th:insert="~{commons :: main}">...</div>
Literals 字面量
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,… 多个值
Text operations: 文本操作
String concatenation: + 拼接
Literal substitutions: |The name is ${name}| 替换
Arithmetic operations:数学运算
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations:布尔运算
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:比较运算
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:条件运算/三元运算符
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:特殊操作
No-Operation: _ 没有操作
Variable Expressions: ${…}
Selection Variable Expressions: *{…} 相比${}的扩展
@RequestMapping("/succ")
public String succ(Map<String,Object> map){
map.put("hello","激动啊");
map.put("id","testid");
map.put("class","testclass");
//
map.put("hello","<h1>你好</h1>");
map.put("users",Arrays.asList("12","34","56"));
//会去找 classpath:/templates/succ.html
return "succ";
}
<!--th:text 将div的值设置为指定值-->
<div th:id="${id}" th:class="${class}" th:text="${hello}"></div>
<!--转义-->
<div th:text="${hello}"></div>
<!--不转义-->
<div th:utext="${hello}"></div>
<!--th:each 每次便利都会生成当前这个标签 3个h4-->
<h4 th:text="${user}" th:each="user:${users}"></h4>
<h4>
<!--3个 span-->
<span th:each="user:${users}">[[${user}]]</span>
</h4>
说明: [[ ]] 相当于 th:text
[()] 相当于 th:utext