1 Web 开发简介
使用 SpringBoot 进行 Web 开发流程:
- 创建项目,勾选所需业务模块
- 框架自动完成场景默认配置,仅需少量自定义配置
- 编写自身业务代码
可探究方向:默认配置细节、配置修改方式、功能扩展实现。
2 静态资源映射规则
底层依靠ResourceProperties、WebMvcAutoConfiguration实现静态资源管控,可自定义缓存周期等参数。
逻辑
java
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META‐INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry
.addResourceHandler(staticPathPattern)
.addResourceLocations(this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
1 webjars 资源访问
匹配路径:/webjars/** 资源真实位置:classpath:/META-INF/resources/webjars/ 以 jar 包引入前端依赖,官网:http://www.webjars.org/
引入 jQuery 示例依赖
XML
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
访问地址:localhost:8080/webjars/jquery/3.3.1/jquery.js
2 普通静态资源访问
路径/**匹配全局请求,依次检索以下目录
- classpath:/META‐INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- 项目根路径
3 欢迎页规则
静态资源目录下index.html为默认首页,访问项目根路径自动匹配跳转。
网站图标配置
默认开启图标拦截,匹配**/favicon.ico请求,可通过配置关闭该功能。
3 模板引擎
常见模板引擎:JSP、Velocity、Freemarker、Thymeleaf SpringBoot 主推Thymeleaf,语法简洁易用。
1 引入依赖
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
项目启动自动加载ThymeleafAutoConfiguration完成自动配置。
默认配置规则
java
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
页面默认存放templates目录,后缀固定.html,配置文件可修改前缀、后缀、编码、缓存等参数。
基础使用演示
- html 页面引入命名空间
html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 控制器封装数据
java
@RequestMapping("/success")
public String hello(Model model){
model.addAttribute("hello","<h1>zhangsan</h1>");
return "success";
}
- 模板页面取值
XML
<div th:text="${hello}"> </div>
2 Thymeleaf 语法
1 标准表达式
- 变量表达式:
${session.user.name}获取域内数据 - 选择表达式:
*{customer.name}配合th:object使用
html
<div th:object="${book}">
<span th:text="*{title}">...</span>
</div>
- 国际化表达式:
#{main.title}读取国际化配置文件 - URL 表达式:
@{/order/list}自动拼接路径,支持传参
html
<a th:href="@{/order/details(id=${orderId})}"></a>
2 表达式支持语法
- 字面量:文本、数字、布尔、null
- 文本操作:字符串拼接、文本替换
- 算术运算:加减乘除取模
- 逻辑运算:与、或、非
- 比较运算:大于、小于、等于判断
- 条件运算:三元表达式、默认值赋值
示例
java
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
3 常用标签汇总
| 关键字 | 作用 | 示例 |
|---|---|---|
| th:id | 替换元素 id | <input th:id="'xxx' + ${collect.id}"/> |
| th:text | 纯文本渲染 | <p th:text="${collect.description}"> |
| th:utext | 解析 html 标签文本 | <p th:utext="${htmlcontent}"> |
| th:object | 绑定实体对象 | <div th:object="${session.user}"> |
| th:value | 表单赋值 | <input th:value="${user.name}" /> |
| th:each | 循环遍历 | <tr th:each="user:${users}"> |
| th:if | 条件判断展示 | <a th:if="${userId == collect.userId}"> |
| th:unless | 反向条件判断 | <a th:unless=${session.user != null}>Login</a> |
| th:href | 跳转链接 | <a th:href="@{/login}"> |
| th:switch/th:case | 多分支判断 | 多条件场景匹配 |
| th:src | 资源路径引入 | <img th:src="@{/img/logo.png}" /> |
| th:action | 表单提交地址 | <form th:action="@{/subscribe}"> |
标签综合测试页面
html
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div th:text="${hello}" th:id="${hello.toUpperCase()}">xxxx</div>
<input th:value="${user.getUsername()}">
<hr>
<div th:object="${user}">
<span th:text="*{username}"></span>
</div>
<a th:if="${user.getAge() == 2}" >年龄</a>
<a th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a>
<p th:if="${user.score >= 60 and user.score < 85}">B</p>
<p th:if="${user.score < 60}">C</p>
<p th:if="${user.score > 85}">优秀</p>
<span th:switch="${user.gender}">
<p th:case="1">男</p>
<p th:case="2">女</p>
</span>
<table>
<tr th:each="a,aState:${uList}">
<td th:text="${a.username}"></td>
<td th:text="${a.password}"></td>
<td th:text="${aState.index}"></td>
</tr>
</table>
</body>
</html>
控制器数据封装代码
java
@RequestMapping("/success")
public String hello(HttpServletRequest req, HttpSession httpSession, Model model){
model.addAttribute("hello","<h1>renliang</h1>");
User user = new User();
user.setPassword("111");
user.setUsername("renliang");
user.setAge(1);
user.setScore(78);
user.setGender(2);
List<User> uList = new ArrayList<>();
for (int i = 0; i < 10; i++){
User u = new User();
u.setUsername("renliang"+i);
u.setPassword("111"+i);
uList.add(u);
}
model.addAttribute("user", user);
model.addAttribute("uList", uList);
return "success";
}
小结
本篇梳理了 SpringBoot Web 开发基础流程,讲解静态资源访问规则,同时完整学习 Thymeleaf 模板引擎的依赖引入、基础语法与常用标签用法,并搭配实操案例完成页面数据渲染,相关基础知识点到此结束,下篇继续讲解 SpringMVC 整合、容器配置等进阶内容。