定义-Inteceptor
使用:以用户登录,注册...为例
创建拦截器类,实现HandlerInterceptor接口,重写preHandle方法,在该方法中编写业务拦截的规则
创建LoginInceptor,实现HandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断session是否存在id HttpSession session = request.getSession(); if (session.getAttribute("id")==null) { //null,没有登录 response.sendRedirect("../user/login.do"); return false; }else { return true; } } }
创建拦截器配置类
使用@Configuration注解将这个类定义为配置类,实现WebMvcConfigurer接口并且重写addInterceptors方法
public class InterceptorConfig implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { //黑名单 List<String> addPathPatterns = new ArrayList<String>(); addPathPatterns.add("/user/**.do"); //白名单 List<String> excludePathPatterns = new ArrayList<>(); excludePathPatterns.add("/user/login.do"); excludePathPatterns.add("/user/reg.do"); //拦截器类 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(addPathPatterns) .excludePathPatterns(excludePathPatterns); } }