视图解析与模板引擎
springboot 默认不支持 jsp,需要引入第三方模板引擎技术
1. 简单语法
1. 表达式
表达式名字 | 语法 | 用途 |
---|---|---|
变量取值 | ${…} | 获取请求域、session域、对象等 |
选择变量 | *{…} | 获取上下文对象值 |
消息 | #{…} | 获取国际化等值 |
链接 | @{…} | 生成链接 |
片段表达式 | ~{…} | jsp:include 作用,引入公共页面 |
2. 字面量
文本值、数字、布尔值、空值、变量(不能有括号)
3. 文本操作
字符串拼接:+
变量替换: |The name is ${name}|
4. 数学运算
运算符:+,-,*,/,%
5. 布尔运算
运算符: and,or
一元运算: !,not
6. 比较运算
>
, < , >= , <=
== , !=
7. 条件运算
(if)?(then)
(if)?(then):(else)
2. 设置属性值(th:attr)
<input value="name" th:attr="value=#{obj.name}">
<input value="name" th:value="#{obj.name}">
3. 引入
<dependency>
<groupId>org.springframework.boot</groupId>
<atrifactId>spring-boot-starter-thymeleaf</atrifactId>
</dependency>
自动配置好 thymeleaf
@Configuration(proxyBeanMethod = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({TemplatMode.class,SpringTemplateEngine.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class,WebFluxAutoConfiguratin.class})
public class ThymeleafAutoConfiguration{}
自动配置好的策略
- 所有的 thymeleaf 配置值都在 ThymeleafProperties
- 配置好了 SpringTemplateEngine
- 配好了 ThymeleafViewResolver
- 只需要开发页面就好
thymeleaf 默认配置 ThymeleafProperties.java
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties{}
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
页面默认放在 /templates/ 下,以 .html 结尾。
4. 编写
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>1</title>
</head>
<body>
info
<h1 th:text="${msg}">test</h1>
</body>
</html>
@Controller
public class ViewTestController{
@GetMapping("/autoTest")
public String autoTest(Model model){
// model 中的数据会被放在请求域中, request.setAttribute("a","info")
model.addAttribute("msg","hello");
return "info";
}
}
Spring Boot DevTools 实时编译