-
Spring Boot项目中的application.properties配置文件一共可以出现在以下四个位置:
- 项目根目录下的config文件夹中
- 项目根目录下
- classpath下的config文件夹中
- classpath下
如果这四个位置都有,则优先级1>2>3>4,如图。
-
如何使用Thymeleaf模板?
STEP1:
在pom.xml里引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>STEP2:
在application.properties中进行配置:
#Thymeleaf配置 #是否开启缓存,默认true spring.thymeleaf.cache=false #检查模板是否存在,默认true spring.thymeleaf.check-template=true #检查模板位置是否存在,默认true spring.thymeleaf.check-template-location=true #模板文件编码 spring.thymeleaf.encoding=UTF-8 #模板文件前缀 spring.thymeleaf.prefix=classpath:/templates/ #Content-Type配置 spring.thymeleaf.servlet.content-type=text/html #模板文件后缀 spring.thymeleaf.suffix=.html Attention!
- 配置模板前缀
spring.thymeleaf.prefix=classpath:/templates/最后一个斜杠“/”不能省略,否则解析不到视图
STEP3:
在resources/templates下创建一个html,标签修改为
<html lang="en" xmlns:th="http://www.thymeleaf.org">即可使用th。 - 配置模板前缀
-
自定义错误页
原理:Spring Boot默认是在error目录下找4xx.html或5xx.html文件作为错误视图,当找不到时会回到errorHtml方法中,然后使用error作为默认的错误页面视图名,如果名为error的视图也找不到,就会展现默认的错误页面。
如何自定义?
- 自定义静态错误页:在resources/static目录下创建error目录,在error目录下创建错误展示页面。可以按4xx.html、5xx.html规则创建,归类所有4或5开头的错误码;也可以直接使用错误码命名文件,如404.html、500.html。
- 自定义动态错误页:假设使用Thymeleaf模板,在/resources/templates目录下创建error目录,创建4xx.html、5xx.html(模板展示信息比较灵活,不需要按响应码创建多个)。
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org/"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <td>TimeStamp</td> <td th:text="${timestamp}"></td> </tr> <tr> <td>status</td> <td th:text="${status}"></td> </tr> <tr> <td>error</td> <td th:text="${error}"></td> </tr> <tr> <td>message</td> <td th:text="${message}"></td> </tr> <tr> <td>path</td> <td th:text="${path}"></td> </tr> </table> </body> </html>当访问不存在的地址时,触发404错误,如图:
当访问一个会抛出异常的地址,触发500错误,如图:
Attention!
- 若用户定义了多个错误页面,则响应码.html的优先级高于4xx.html、5xx.html。例如:404.html > 4xx.html。
- 动态页面的优先级高于静态页面,即若
resources/static/error和resources/templates/error下同时定义了404.html,则优先展示resources/templates/error/404.html。
-
CORS:配置跨域有两种方式
- 全局跨域配置
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/book/**") .allowedHeaders("*") .allowedMethods("*") .maxAge(1800) .allowedOrigins("http://localhost:8081"); } }-
addMapping表示对哪种格式的请求路径进行跨域处理 -
allowedHeaders表示允许的请求头,默认允许所有的请求头信息 -
allowMethods表示允许的请求方法,默认是POST、GET和HEAD -
maxAge表示探测请求的有效期,默认是1800秒,即30分钟 -
allowedOrigins表示支持的域
-
@CrossOrigin注解配置:在需要配置跨域的方法或类前加上
@CrossOrigin(value="http://localhost:8080",maxAge=1800,allowedHeaders="*")注解,可以控制单个方法的跨域。
-
未完