美文网首页spring
SpringBoot-拦截器与过滤器

SpringBoot-拦截器与过滤器

作者: Tian_Peng | 来源:发表于2020-05-09 16:12 被阅读0次

SpringBoot中使用拦截器

在传统的SSM架构中,我们想使用拦截器,一般步骤如下:

  • 自定义一个拦截器继承自HandlerInterceptorAdapter
  • 在Spring-MVC的配置文件中增加拦截器配置
    例如:
<!--springMvc拦截器配置-->
<mvc:interceptors>
  <mvc:interceptor>
    <!-- 拦截所有的请求,这个必须写在前面,也就是写在【不拦截】的上面 -->
    <mvc:mapping path="/**" />
    <!-- 但是排除下面这些,也就是不拦截请求 -->
    <mvc:exclude-mapping path="/toLogin" />
    <mvc:exclude-mapping path="/doLogin" />
    <bean class="com.tp.interceptors.UserLoginInterceptor" />
  </mvc:interceptor>
</mvc:interceptors>

在SpringBoot中,我们一般采用JavaConfig的方式进行配置,具体步骤如下:

  • 自定义一个拦截器继承自HandlerInterceptorAdapter
    例如:
public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object username = session.getAttribute(LoginConstants.LOGIN_KEY);
        if (null == username) {
            request.getRequestDispatcher("/toLoginPage").forward(request, response);
            return false;
        } else {
            return true;
        }
    }
}
  • 编写一个配置类,实现WebMvcConfigurer接口,重写addInterceptors()方法
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {  //该参数为拦截器注册器;
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/doLogin", "/toLoginPage", "/static/**");
    }
}

至此,拦截器就生效啦

SpringBoot中使用过滤器

Springboot中使用过滤器有2种方式:

  • 注解形式
    创建一个Filter,并使用WebFilter注解进行修饰,表示该类是一个Filter,以便于启动类进行扫描的时候确认
@WebFilter(urlPatterns = "/*", filterName = "annotationFilter")
public class AnnotationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("基于注解的过滤器执行了.....");
        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("基于注解的过滤器初始化.....");
    }

    @Override
    public void destroy() {
        System.out.println("基于注解的过滤器被销毁.....");
    }
}

然后在启动类中增加注解@ServletComponentScan

@ServletComponentScan
@SpringBootApplication
public class BootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class, args);
    }
}

启动项目访问任意一个现有接口测试:

  • 代码形式
    同样编写Filter,但是不添加WebFilter注解,通过@Bean注入spring
public class CodeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("基于代码的过滤器执行了.....");
        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("基于代码的过滤器初始化.....");
    }

    @Override
    public void destroy() {
        System.out.println("基于代码的过滤器被销毁.....");
    }
}

编写一个配置类注册此过滤器:

@Configuration
public class FilterConfig {

    @Bean
    @Order(2) //spring boot会按照order值的大小,从小到大的顺序来依次过滤
    public FilterRegistrationBean configFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new CodeFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("codeFilter");
        return filterRegistrationBean;
    }
}

启动项目访问任意一个现有接口测试:

相关文章

网友评论

    本文标题:SpringBoot-拦截器与过滤器

    本文链接:https://www.haomeiwen.com/subject/aoucnhtx.html