Springboot拦截器(Interceptor)
一、自定义拦截器
public class MyInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
LoginDTO user = (LoginDTO) session.getAttribute("user");
System.out.println(user);
if(ObjectUtils.isEmpty(user)){
System.out.println("被拦截");
return false;
}else {
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
二、设置拦截器的配置类(让拦截器生效(配置))
/**
* 自定义拦截器的配置类
* @author
* @action
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login");
}
}
@Configuration:告诉springboot,该类为配置类
三、结论
① preHandler 方法在Controller中方法执行之前去执行
② postHandler 在Controller中方法执行之后执行
③ afterCompletion 本次请求完成后执行
④ 类似AOP
⑤ Handler 处理器:springmvc 中Controller 中的方法叫Handler (处理器)