第四章 Spring Boot Web 开发
1、web 开发简介
- 创建 SpringBoot 应用,选中需要的模块
- 使用 SpringBoot 自动配置
- 编写业务代码
@AutoConfiguration 自动配置组件 @Properties 封装配置文件的内容
webjars&静态资源映射规则
1、webjars
配置类:WebMvcAutoConfiguration
webjars 以 jar 包的方式引入静态资源
资源路径映射
/webjars/**
=>
classpath:/META-INF/resources/webjars/
添加 jquery 依赖
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
访问路径
/webjars/jquery/3.5.1/jquery.js
2、静态资源映射规则
静态资源文件夹
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/ 当前项目根路径
默认静态文件下查找
# 欢迎页面
index.html
# 图标路径
favicon.ico
自定义静态资源文件路径,默认资源路径失效
spring.resources.static-locations=classpath:/hello/
引入 thymeleaf
JSP、Velocity、Thymeleaf、Freemarker
模板引擎
Template ${name} + Data {"name": "Tom"} => TemplateEngine => output
Thymeleaf 依赖
<properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 切换 thymeleaf version --> <!-- thymeleaf3 适配 layout2 --> <springboot-thymeleaf.version>2.1.1.RELEASE</springboot-thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> </properties> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>${springboot-thymeleaf.version}</version> </dependency>
thymeleaf 语法
默认配置
public class ThymeleafProperties { private String prefix = "classpath:/templates/"; private String suffix = ".html"; }
模板使用示例
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap; @Controller public class IndexController { @RequestMapping("/hello") public String hello(HashMap<String, Object> map){ map.put("name", "Tom"); // 模板路径 // src/main/resources/templates/about.html return "hello"; } }
模板:
src/main/resources/templates/about.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Title</title> </head> <body> <h1>Hello</h1> <!-- 设置文本内容 --> <div th:text="${name}"></div> </body> </html>
语法规则
th: 任意html属性,用来替换原生属性的值 th:text 改变文本内容(转义) th:utext 改变文本内容(不转义) th:attr th:href th:src th:each th:for
表达式
${} 变量表达式 获取变量值 获取变量属性 调用方法 内置基本对象: #ctx #session... 内置工具对象: *{} 选择表达式 配合th:object使用 #{} 获取国际化内容 @{} 定义url ~{} 片段表达式 字面量 数学运算 布尔运算 比较运算 条件运算 特殊操作
示例
<!--文本输出-->
<div th:text="${name}"></div>
<!--循环遍历-->
<div th:each="pet: ${pets}">
<div>[[${pet}]]</div>
</div>
<!--循环遍历-->
<div th:each="pet: ${pets}" th:text="pet"></div>
SpringMVC 自动配置原理
SpringBoot 对 SpringMVC 默认配置
自动配置
ViewResolver 视图解析器 根据方法返回值的到视图对象(View) 视图对象决定如何渲染、转发、重定向 Converter 类型转换器 Formatter 格式化器 HttpMessageConverters 转换请求响应 MessageCodesResolver 定义错误代码生成规则 WebDataBinder 数据绑定器
修改 SpringBoot 默认配置
优先使用用户配置@Bean/@Component
如果没有才自动配置
有些组件可以有多个
eg: ViewResolver 将用户配置和默认配置组合起来