Java中的
⼀. 的概念和作⽤
(Interceptor)是⼀种动态拦截⽅法调⽤的机制,在SpringMVC中动态拦截控制器⽅法的执⾏
作⽤:
1. 在指定的⽅法调⽤前后执⾏预先设定的代码
2. 阻⽌原始⽅法的执⾏
3. 总结:增强
核⼼原理:AOP思想
⼆. 和过滤器的区别
归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
拦截内容不同:Filter对所有访问进⾏增强,Interceptor仅针对SpringMVC的访问进⾏增强
三. 代码实现
【第⼀步】定义
做法:定义⼀个类,实现HandlerInterceptor接⼝即可
@Component //注意当前类必须受Spring容器控制
//定义类,实现HandlerInterceptor接⼝
public class ProjectInterceptor implements HandlerInterceptor {
@Override
//原始⽅法调⽤前执⾏的内容
//返回值类型可以拦截控制的执⾏,true放⾏,false终⽌
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  System.out.println(""+contentType);
  return true;
}
@Override
//原始⽅法调⽤后执⾏的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
modelAndView) throws Exception {
  System.out.println("");
}
@Override
//原始⽅法调⽤完成后执⾏的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  System.out.println("");
  }
}
【第⼆步】配置加载
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
  @Autowired
  private ProjectInterceptor projectInterceptor;
  @Override
  protected void addInterceptors(InterceptorRegistry registry) {
  //配置
  registry.addInterceptor(projectInterceptor)
  .addPathPatterns("/books","/books/*");
  }
}
使⽤标准接⼝WebMvcConfigurer简化开发(注意:侵⼊式较强) @Configuration
@ComponentScan({"ller"})
@EnableWebMvc
//实现WebMvcConfigurer接⼝可以简化开发,但具有⼀定的侵⼊性public class SpringMvcConfig implements WebMvcConfigurer {
  @Autowired
  private ProjectInterceptor projectInterceptor;
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
  //配置多
  registry.addInterceptor(projectInterceptor)
  .addPathPatterns("/books","/books/*");
  }
}springboot和过滤器

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。