资源速查-SSM整合-拦截器入门案例

推荐先阅读Spring全家桶

1.制作拦截器功能类

2.配置拦截器的执行位置

// 声明拦截的bean,并实现HandlerInterceptor接口(注意:扫描加载bean)
@Component
public class ProjectInterceptor implements HandlerInterceptor {
public boolean preHandler(..) throws Exception {
System.out.println("preHandler...");
}
public boolean postHandler(..) throws Exception {
System.out.println("postHandler...");
}
public boolean afterCompletion(..) throws Exception {
System.out.println("afterCompletion...");
}
}
// 定义配置类,继承WebMvcConfigurationSupport,实现addInterceptor方法(注意:扫描加载bean)
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry){
// 添加拦截器并设定拦截的访问路径,路径可以通过可变参数设置多个
registry.addInterceptor(projectInterceptor).addPathPatterns("/books");
}
}

也可以使用标准接口WebMvcConfigure简化开发(注意:侵入性较强)

@Configuration
@ComponentScan("com.zx.controller")
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
}

拦截器执行流程

image-20220814211749428