温馨提示×

温馨提示×

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

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

SpringBoot中Filter和Interceptor如何使用

发布时间:2021-06-25 16:44:39 来源:亿速云 阅读:150 作者:Leah 栏目:编程语言

SpringBoot中Filter和Interceptor如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一、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容器中使用拦截器

@Configurationpublic 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。

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

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

AI