温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Filter和Interceptor怎么在SpringBoot中使用

发布时间:2021-03-24 17:20:35 来源:亿速云 阅读:233 作者:Leah 栏目:编程语言

本篇文章为大家展示了Filter和Interceptor怎么在SpringBoot中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、Filter(过滤器)

Filter接口定义在javax.servlet包中,是Servlet规范定义的,作用于Request/Response前后,被Servlet容器调用,当Filter被Sring管理后可以使用Spring容器资源。

实现一个Filter

自定义的过滤器需要实现javax.servlet.Filter,Filter接口中有三个方法:

  • init(FilterConfig filterConfig):过滤器初始化的被调用。

  • doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain):在doFilter()方法中,chain.doFilter()前的一般是对request执行的过滤操作,chain.doFilter后面的代码一般是对response执行的操作,chain.doFiter()执行下一个过滤器或者业务处理器。

  • destory():过滤器销毁的时候被调用。

在Spring容器中使用过滤器

通过FilterRegistrationBean

 @Configuration
 public class WebConfig{
  @Bean
  public FilterRegistrationBean xxxFilter() {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new xxxFilter());
    registrationBean.setUrlPatterns(Arrays.asList("/*"));
    registrationBean.setOrder(1); // 过滤器的优先级
    return registrationBean;
  }
}

通过@WebFilter和@ServletComponentScan

通过@WebFilter的方式定义Filter,默认使用Filter的类名设置优先级。使用FilterRegistrationBean可以指定优先级。Filter使用白名单过滤Url的方式,配置需要拦截的Url,如果想设置不过滤某些Url需要在doFilter方法中指定。

二、Interceptor(拦截器)

定义一个Interceptor需要实现org.springframework.web.servlet.HandlerInterceptor接口,Interceptor是Spring容器定义的,它可以使用Spring容器的任何资源,只要通过IoC注入到Interceptor即可,Interceptor可以深入到业务处理方法的执行前后和抛出异常的时候,而Filerter无法做到这一点,所以Interceptor相比Filter具有更大的弹性。

实现一个Interceptor

实现HandlerInterceptor或者继承HandlerInterceptorAdapter

public interface HandlerInterceptor {
  default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    return true;
  }

  default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
  }

  default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
  }
}
  • preHandle:在业务处理器处理请求之前被调用。

  • postHandle:在业务处理器处理请求后并生成视图前被调用,此时有机会修改ModelAndView。

  • afterCompletion:业务处理处理器处理完请求后(已经渲染视图)被执行,并可以处理业务方法发生异常的场景。

在Spring容器中使用拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    InterceptorRegistration registration = registry.addInterceptor(new TimeInterceptor());
    registration.excludePathPatterns("/user");
    registration.excludePathPatterns("/*");
  }
}

Interceptor既可以指定要过滤的Url也可以指定不拦截的Url,缺省情况拦截所有Url。

上述内容就是Filter和Interceptor怎么在SpringBoot中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI