拦截器
- 1.编写一个拦截器实现HandlerInterceptor接口
- 2.拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
- 3.指定拦截规则[如果是拦截所有,静态资源也会被拦截]
1、HandlerInterceptor 接口
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String requestURI = request.getRequestURI();log.info("preHandle拦截的请求路径是{}",requestURI);HttpSession session = request.getSession();Object loginUser = session.getAttribute("loginUser");if(loginUser != null){return true;}request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/").forward(request,response);return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("postHandle执行{}",modelAndView);}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {log.info("afterCompletion执行异常{}",ex);}
}
2、配置拦截器
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**") .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); }
}
test
- 执行顺序