springboot集成过滤器

Posted 未月廿三

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot集成过滤器相关的知识,希望对你有一定的参考价值。

封装自定义接口filter

包含两个方法,第一个过滤的路径数组,第二个为过滤器执行的顺序.spring boot 会按照order值的大小,从小到大的顺序来依次过滤。

package com.theeternity.common.baseFilter;

import javax.servlet.Filter;

/**
 * @program: ApiBoot
 * @description: 封装Filter
 * @author: TheEternity Zhang
 * @create: 2019-02-17 13:08
 */
public interface MappingFilter extends Filter {
    String[] addUrlPatterns();

    int order();
}

书写具体的filter

package com.theeternity.beans.filterConfig;

import com.theeternity.common.baseFilter.MappingFilter;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import java.io.IOException;

/**
 * @program: ApiBoot
 * @description: 权限过滤器
 * @author: TheEternity Zhang
 * @create: 2019-02-17 13:14
 */
public class AuthFilter implements MappingFilter {

    @Override
    public String[] addUrlPatterns() {
        return new String[]{"/*"};
    }

    @Override
    public int order() {
        return 0;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //具体逻辑
    }

    @Override
    public void destroy() {

    }

}

注入bean到容器

package com.theeternity.beans.filterConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @program: ApiBoot
 * @description: 注册过滤器
 * @author: TheEternity Zhang
 * @create: 2019-02-17 13:10
 */
@Configuration
public class FilterConfig {

    private Logger logger= LoggerFactory.getLogger(FilterConfig.class);

    @Bean
    public FilterRegistrationBean registFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        AuthFilter authFilter=new AuthFilter();
        registration.setFilter(authFilter);
        registration.addUrlPatterns(authFilter.addUrlPatterns());
        registration.setOrder(authFilter.order());
        registration.setName("AuthFilter");
        return registration;
    }

}

以上是关于springboot集成过滤器的主要内容,如果未能解决你的问题,请参考以下文章

springboot Thymeleaf 整合

springboot2.x集成dubbo (支持不同group不同注册中心)

Spring boot + mybatis + 多数据源入门搭建 + 跨域集成以及过滤器配置的方式和过滤器加载顺序控制

spring boot 整合 redis

springboot集成elk 一: springboot + Elasticsearch

SpringBoot启动报错“Consider defining a bean of type ‘xxx.mapper.UserMapper‘ in your configuration.“(代码片段