新增spring mvc关于interceptor文档

This commit is contained in:
wuxiangkai
2023-10-30 21:21:45 +08:00
parent 4e686152a4
commit b856a9af7b
2 changed files with 48 additions and 0 deletions

29
java se/juc.md Normal file
View File

@@ -0,0 +1,29 @@
# juc
## ThreadLocal
通过ThreadLocal api可以存储对象并且存储的对象只有指定线程才能够访问。
### 示例
```java
// 声明一个ThreadLocal对象其中存储的Integer值和特定线程绑定
ThreadLocal<Integer> threadLocalVlaue = new ThreadLocal<>();
// 再特定线程中调用get/set方法可以对与该线程绑定
// 的integer值进行获取或设置
threadLocalValue.set(1);
Integer result = threadLocalValue.get();
```
ThreadLocal类似于一个map其中key为线程value为与线程绑定的值再特定线程中调用
### api
#### withInitial
可以通过`ThreadLocal.withInitial`方法来构造一个带初始值的threadLocal对象该静态方法接收一个supplier对象。
```java
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
```
如果一个ThreadLocal对象指定了withInitial方法那么当该ThreadLocal对象get为空时会调用withInitial并用该方法的返回值来初始化该threadLocal对象。
#### remove
如果要移除ThreadLocal中的对象可以调用`remove`方法
```java
threadLocal.remove();
```

View File

@@ -59,6 +59,7 @@
- [CORS](#cors)
- [@CrossOrigin](#crossorigin)
- [spring boot全局配置CORS](#spring-boot全局配置cors)
- [Interceptor](#interceptor)
# SpringMVC
@@ -800,3 +801,21 @@ public class WebConfig implements WebMvcConfigurer {
}
```
### Interceptor
通过注册拦截器,可以在请求的请求前、请求后阶段进行处理。
interceptor可以通过如下方式进行注册
```java
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
}
}
```
其中如果多次调用addInterceptor添加拦截器那么拦截器顺序即是添加顺序。