展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

ssm整合(七):拦截器参数和拦截器链

  • 拦截器参数
@Component
//定义拦截器类,实现HandlerInterceptor接口
//注意当前类必须受Spring容器控制
public class ProjectInterceptor implements HandlerInterceptor {

    @Override
    //原始方法调用前执行的内容
    //返回值类型可以拦截控制的执行,true放行,false终止
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的数据
        String contentType = request.getHeader("Content-Type");
        // 获取要操作的那个方法
        HandlerMethod hm = (HandlerMethod)handler;
        System.out.println("preHandle..."+contentType);
        return true;
    }

    @Override
    //原始方法调用后执行的内容
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    //原始方法调用完成后执行的内容
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }

}
  • 配置多个拦截器
@Component
public class ProjectInterceptor2 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...222");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...222");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...222");
    }

}

@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ProjectInterceptor projectInterceptor;

    @Autowired
    private ProjectInterceptor2 projectInterceptor2;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置多拦截器
        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
        registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
    }

}
  • 拦截器执行顺序

  • 当2个拦截器都设置为true时,执行顺序如下

  • 将第1个拦截器设置为false,第2个拦截器设置为true

  • 拦截器的运行顺序参照拦截器的添加顺序

  • 例如配置3个拦截器,执行顺序如下

  • 配置3个拦截器,第1个设置为false,第2、3设置为true,则只执行第1个拦截器的preHandle方法

  • 当3个拦截器都设置为false时,则执行3个拦截器的前置,3个postHandle都不执行,最后执行第2个和第1个拦截器的afterCompletion

  • 当第1个和第2个拦截器设置为false时,则执行前2个拦截器的前置,3个postHandle都不执行,最后执行第1个拦截器的afterCompletion

  • 当第1个拦截器设置为false时,则执行第1个拦截器的前置,3个postHandle都不执行,最后3个拦截器的afterCompletion也都不会执行

posted @ 2022-05-25 22:32  DogLeftover  阅读(38)  评论(0编辑  收藏  举报