编写拦截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
}
@Override
public void postHandle ( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion ( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
对于前后端分离架构
preHandle 会在方法执行前执行,按照拦截器顺序执行 postHandle 会在方法return前执行,按照拦截器顺序逆序执行 afterCompletion 方法return 之后执行 ,按照拦截器顺序逆序执行
拦截器注册
@Component
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors ( InterceptorRegistry registry) {
registry. addInterceptor ( new LoginInterceptor ( ) ) . order ( 1 ) ;
}
}