SpringBoot 2.X 过滤器


在SpringBoot中使用使用过滤器有两种,一种是使用注解@WebFilter,第二种是FilterRegistrationBean

@WebFilter实现

@WebFilter用于一个类声明过滤器,该注解将会在部署时被容器处理,容器将根据具体的属性将相应的类部署为过滤器

属性名 类型 描述
filterName String 指定该Filter的名称
urlPatterns String 指定该Filter所拦截的URL
value String 与urlPatterns一致

创建一个MyFilter.java 并且实现Filter接口

package net.auio.filter.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/api/*",filterName = "myFilter")
@Order(1) //指定过滤器的执行顺序,值越大越靠后执行
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(this.getClass().getName()+"被初始化....");
    }

    @Override
    public void destroy() {
        System.out.println(this.getClass().getName()+"被销毁....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest httpServletRequest =(HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        String method = httpServletRequest.getMethod();
        System.out.println("请求URL:"+requestURI+"----请求方式:"+method);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

启动类上加上@ServletComponentScan注解

package net.auio.filter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class FilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(FilterApplication.class, args);
    }

}

创建一个FilterController接口

package net.auio.filter.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
public class TestController {

    @GetMapping(value = "/user/filter")
    public String hello(){
      return "通过FIlter,QAQ~";
    }
}

测试


FilterRegistrationBean 实现

创建MyFilerConfig

package net.auio.filter.config;

import net.auio.filter.filter.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyFilerConfig {


    @Bean
    public MyFilter myFilter(){
        return  new MyFilter();
    }

    @Bean
    public  FilterRegistrationBean filterRegistrationBean(MyFilter myFilter){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(myFilter);
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.addUrlPatterns("/api/*");
        filterRegistrationBean.setName("myFilter");
        return  filterRegistrationBean;
    }
}

修改MyFilter.java

删除注解,或者注释

//@WebFilter(urlPatterns = "/api/*",filterName = "myFilter")
//@Order(1) //指定过滤器的执行顺序,值越大越靠后执行

启动类删除@ServletComponentScan

package net.auio.filter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
public class FilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(FilterApplication.class, args);
    }

}

测试


过滤校验用户是否登录实战

修改application.properties加入开发接口通配地址

#凡是请求地址层级带有 open都放行
open.url=/**/open/**

修改myFilter

package net.auio.filter.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


//@WebFilter(urlPatterns = "/api/*",filterName = "myFilter")
//@Order(1) //指定过滤器的执行顺序,值越大越靠后执行
public class MyFilter implements Filter {

    @Value("${open.url}")
    private String openUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(this.getClass().getName()+"被初始化....");
    }

    @Override
    public void destroy() {
        System.out.println(this.getClass().getName()+"被销毁....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest httpServletRequest =(HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        String method = httpServletRequest.getMethod();
        System.out.println("请求URL:"+requestURI+"----请求方式:"+method);
        //判断是否开放性API
        PathMatcher pathMatcher=new AntPathMatcher();
        if (pathMatcher.match(openUrl,requestURI)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            String token = httpServletRequest.getHeader("token");
            if(StringUtils.isEmpty(token)){
                servletRequest.getRequestDispatcher("/api/open/unLogin").forward(servletRequest, servletResponse);
            }else{
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
        //判断是否携带凭证

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

新增未登录接口,首页接口

package net.auio.filter.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
public class FilterController {

    @GetMapping(value = "/user/filter")
    public String hello(){
      return "我被MYFILTER监视了";
    }


    @GetMapping(value = "/home/open/info")
    public String getHome(){
       return "欢迎访问首页";
    }

    @GetMapping(value = "/open/unLogin")
    public String getUnLogin(){
        return "登录失效,请重新登录!";
    }
}

测试

访问未开放得接口

访问开放接口

携带TOKEN访问受保护得接口

posted @ 2020-08-03 00:56  余慕秦丿  阅读(639)  评论(0编辑  收藏  举报