拦截器 实现 spring家的handlerInterceptor
可以看下就是拦截前 中 后
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
拦截器类+threadLocal
threadlocal中的类型为 实现serilaizeble的序列化的Vo
@Component
public class MyInterceptor implements HandlerInterceptor {
private static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession().getAttribute("loginUser") == null) {
response.sendRedirect("http://www.baidu.com");
return false;
} else {
threadLocal.set((MemberRespVo) request.getSession().getAttribute("loginUser"));
System.out.println("获得了"+threadLocal.get());
return true;
}
}
}
拦截器配置类 在容器中加入拦截器 让它对应的url中生效
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}