springboot集成过滤器

2020-01-30 16:04:14来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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;
    }

}

原文链接:https://www.cnblogs.com/eternityz/p/12243201.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:springboot集成rabbitmq

下一篇:idea中MavenWeb项目不能创建Servlet的解决办法