//登陆拦截器public class LoginInterceptor implements HandlerInterceptor { //访问controller之前被调用 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session=request.getSession(); if(null!=session.getAttribute("admin")) return true; return false; } //访问controller之后 访问视图之前被调用 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } //访问视图之后被调用 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
拦截器配置类 @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { // 多个拦截器组成一个拦截器链 // addPathPatterns 用于添加拦截规则 // excludePathPatterns 用户排除拦截 registry.addInterceptor(new LoginInterceptor()) //添加拦截器 .addPathPatterns("/**") //拦截所有请求 .excludePathPatterns("/","/admin_login","/login"); //对应的不拦截的请求 super.addInterceptors(registry); } }