@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加自定义拦截器
registry.addInterceptor(new CartInterceptor()).addPathPatterns("/**");
}
}
public class CartInterceptor implements HandlerInterceptor {
//线程内部的存储类,可以在指定线程内存储数据,数据存储以后,只有指定线程可以得到存储数据
public static ThreadLocal threadLocal = new ThreadLocal();
/**
* 目标方法前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("业务逻辑~");
Map<String,Object> data = new HashMap<>();
threadLocal.set(data);
return true;
}
//只要是同一线程,都可以使用threadLocal.get();获取当前线程变量
/**
* 任务执行之后
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
/**
* ThreadLocal set时是Entry(key, value)set进ThreadLocalMap,
* 而Entry是extends WeakReference<ThreadLocal<?>>的,
* 所以当ThreadLocal=null时,GC会把ThreadLocal回收,但是Thread不死,ThreadLocalMap就会一直存在 ,
* GC把ThreadLocal回收后,ThreadLocalMap还存在一条无用的信息(key没了,value还在),
* 这样就造成了内存泄漏,所以在ThreadLocal使用完成后,请调用remove方法
*/
threadLocal.remove();
}
/**
* 视图渲染之后
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}