文章目录
一、Springboot 自动转配原理
1、@Controller 与@RestController 的区别
- 页面跳转使用 @Controller,使用@Controller注解,需要返回数据的方法要加@ResponseBody
- 获取数据使用 @RestController,相当于@ResponseBody + @Controller合在一起的作用
- @Controller 与@RestController 都只能使用在class上,不能使用在方法上
二、thymeleaf 模板引擎(了解,建议学习VUE)
1、增加 spring-boot-starter-thymeleaf 依赖:
- spring-boot-starter-thymeleaf:自动装配 Thymeleaf 模板引擎
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、YML配置 Thymeleaf属性
application.yml
spring:
thymeleaf:
cache: false # 是否开启模板缓存,默认为:true,开发时关闭缓存,不然没法看到实时页面!
mode: HTML # 指定模板的模式,默认为:HTML
encoding: UTF-8 # 指定模板的编码,默认为:UTF-8
prefix: classpath:/templates/ # 指定模板的前缀,默认为:classpath:/templates/
suffix: .html # 指定模板的后缀,默认为:.html
servlet:
content-type: text/html # 指定 Content-Type 值,默认为:text/html
3、引入命名空间:
<html xmlns:th="http://www.thymeleaf.org">
4、简单表达式
4.1 ${…} 变量表达式 :
使用方法:直接使用th:xx = “${}” 获取对象属性 。例如:
<form id="userForm">
<input id="id" name="id" th:value="${user.id}"/>
<input id="username" name="username" th:value="${user.username}"/>
<input id="password" name="password" th:value="${user.password}"/>
</form>
<div th:text="hello"></div>
<div th:text="${user.username}"></div>
4.2 *{…} 选择变量表达式:
使用方法:首先通过th:object 获取对象,然后使用th:xx = "*{}"获取对象属性
<form id="userForm" th:object="${user}">
<input id="id" name="id" th:value="*{id}"/>
<input id="username" name="username" th:value="*{username}"/>
<input id="password" name="password" th:value="*{password}"/>
</form>
4.3 #{…} 消息表达式:
通常用于的获取国际化属性:th:xx="#{} "用于获取国际化语言翻译值。例如:
<title th:text="#{user.title}"></title>
4.4 @{…} 链接url表达式
使用方法:通过链接表达式@{}直接拿到应用路径,然后拼接静态资源路径。例如:
<a th:href="@{http://www.baidu.com}">跳转百度</a>
<script th:src="@{/webjars/jquery/jquery.js}"></script>
<link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">
三、LOMBOK 结构化插件
- 创建实体类:
@Data
@AllArgsConstructor //全参构造函数
@NoArgsConstructor //无参构造函数
public class Deptment {
private Integer id;
private String deptName;
}
- 初始化实体:(使用全参注释@AllArgsConstructor 效果)
四、i18n国际化
- 创建国际化i18n包
- 创建国际语言
- 定义国际化字段
- 配置国际化
- 使用国际化地段,使用#{ }
IDEA 创建i18n的文件夹,并创建国际化语言
使用idea 的可视化Resource bundle 工具定义国际化字段
配置国际化文件
spring:
messages:
basename: i18n.index #配置国际化i18n文件位置
使用thymeleaf语法使用国际化配置
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<body>
<h1 th:text="#{ index.uesr}"></h1>