springboot(5)——拦截器

版权声明:本文出自mqy1023的博客,转载必须注明出处。 https://blog.csdn.net/mqy1023/article/details/79887906
  • 1、使用注解@Configuration配置拦截器
  • 2、继承WebMvcConfigurerAdapter
  • 3、重写addInterceptors 注册添加需要的拦截器,匹配地址

编写一个监听器

// CommonInterceptor.java 获取项目基本路径并设置到httpServletRequest属性值中

public class CommonInterceptor implements HandlerInterceptor {

    /**
     * 请求处理之前调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String path = httpServletRequest.getContextPath();
        String scheme = httpServletRequest.getScheme();
        String serverName = httpServletRequest.getServerName();
        int port = httpServletRequest.getServerPort();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        httpServletRequest.setAttribute("basePath", basePath);
        return true;
    }

    /**
     * 请求处理之后调用, 但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用, 也就是在DispatcherServlet 渲染了对应的视图之后执行
     * (主要用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}

注册监听器

@Configuration
public class CommonInterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器, 按顺序执行
        registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");; // addPathPatterns("/api/**");

        //   /a/** 和 /b/**的请求 要经过AInterceptor 拦截
//        registry.addInterceptor(new AInterceptor()).addPathPatterns("/a/**").addPathPatterns("/b/**");
    }
}
  • 1、拦截器按顺序执行
  • 2、addPathPatterns 添加路径匹配
  • 3、preHandlepostHandleafterCompletion 拦截器回调中 return true; 为放行。前面监听到的拦截器不放行(return false;)的话,后面的拦截器监听不到(不执行)

猜你喜欢

转载自blog.csdn.net/mqy1023/article/details/79887906
今日推荐