springMVC拦截器

springMVC拦截器_第1张图片

和过滤器的区别

和过滤器的区别!:

Filter属于Servlet技术,拦截器属于SpringMVC技术

前者所有访问增强,后者仅对SpringMVC进行增强

 

 制作拦截器

1.写拦截器类

2.配置拦截的位置

@Component
public class Projectinterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

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

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

@Configuration
public class SpringMVCSupport extends WebMvcConfigurationSupport {
    @Autowired
    private Projectinterceptor projectinterceptor;


    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        System.out.println("22222");
        //配置拦截器 当访问books路径时执行
        registry.addInterceptor(projectinterceptor).addPathPatterns("/books","/books/*");
    }
}
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig  implements WebMvcConfigurer{
    @Autowired
    private Projectinterceptor projectinterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("22222");
        //配置拦截器 当访问books路径时执行
        registry.addInterceptor(projectinterceptor).addPathPatterns("/books","/books/*");
    }


}

springMVC拦截器_第2张图片

 拦截器参数分析

关键是Handler封装了Method方法

springMVC拦截器_第3张图片

 拦截器链

@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig  implements WebMvcConfigurer{
    @Autowired
    private Projectinterceptor projectinterceptor;

    @Autowired
    private Projectinterceptor projectinterceptor2;


    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("22222");
        //配置拦截器 当访问books路径时执行
        registry.addInterceptor(projectinterceptor).addPathPatterns("/books","/books/*");
        registry.addInterceptor(projectinterceptor2).addPathPatterns("/books","/books/*");
    }


}

你可能感兴趣的:(java,java,spring)