SpringMVC拦截器实例

实现HandlerInterceptor接口,该接口中都是默认方法,所以需要哪个 重写哪个

HandlerInterceptor源码:

public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

重写preHande() 返回值决定是否放行

public class TimeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("===preHandle===");
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        if (hour<12 || hour>18)
            throw new RuntimeException("请在9~18进行访问");
        return true;
    }
}

拦截器写完后,需要配置,WebMvcConfigurer接口中都是default方法,在这里只需要重写addInterceptors方法,在该方法中注册拦截器并定义拦截规则

@Component
public class ImterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TimeInterceptor())//注册拦截器
                .addPathPatterns("/provider/doSentinel1");//定义拦截规则
    }
}

上一篇:SpringMVC和SpringBoot的区别


下一篇:SpringBoot 创建SpringMVC项目