在SpringBoot中实现自定义拦截器

  1. 创建类实现SpringMVC框架的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 {
    }
    }
  2. SpringBoot中注册拦截器:

    @Configuration
    public class MyAppConfig implements WebMvcConfigurer {
    //添加拦截器对象, 注入到容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    //创建拦截器对象
    HandlerInterceptor interceptor = new LoginInterceptor();
    //指定拦截的请求uri地址
    String path []= {"/user/**"};
    //指定不拦截的地址
    String excludePath [] = {"/user/login"};
    registry.addInterceptor(interceptor)
    .addPathPatterns(path)
    .excludePathPatterns(excludePath);
    }
    }
posted @   z-laoyao  阅读(288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示