欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在springboot中如何使用filter設(shè)置要排除的URL

 更新時(shí)間:2021年12月24日 16:04:50   作者:Airbundey  
這篇文章主要介紹了在springboot中如何使用filter設(shè)置要排除的URL,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用filter設(shè)置要排除的URL

@WebFilter(urlPatterns = "/*")
@Order(value = 1)
public class TestFilter implements Filter {
 
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/main/excludefilter", "/login", "/logout", "/register")));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init-----------filter");
    }
 
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
 
        if (allowedPath) {
            System.out.println("這里是不需要處理的url進(jìn)入的方法");
            chain.doFilter(req, res);
        }
        else {
            System.out.println("這里是需要處理的url進(jìn)入的方法");
        }
    }
 
    @Override
    public void destroy() {
        System.out.println("destroy----------filter");
    }
}

@Order中的value越小,優(yōu)先級(jí)越高。

  • ALLOWED_PATHS

這個(gè)是一個(gè)集合,存放的是需要排出的URL,用來(lái)判斷是否是需要排除的URL。

關(guān)于為什么SpringBoot中使用了@WebFilter但是過(guò)濾器卻沒(méi)有生效:一定要加上@Configuration注解,@Service其實(shí)也可以,其他類似。

filter指定過(guò)濾URL的常見(jiàn)問(wèn)題

在使用Filter對(duì)一些自己指定的URL進(jìn)行過(guò)濾攔截時(shí)

經(jīng)常會(huì)出現(xiàn)如下錯(cuò)誤

1、 明明在@WebFilter(urlPatterns={"/app/online"})中過(guò)濾的是/app/online 路徑,但是運(yùn)行之后發(fā)現(xiàn),這個(gè)WebFilter過(guò)濾器對(duì)所有的URL都進(jìn)行了過(guò)濾。

2、 運(yùn)行之后發(fā)現(xiàn)過(guò)濾器沒(méi)有初始化,沒(méi)有被加載

下面總結(jié)一下使用正確的

合適的注解配置filter的方法:

1、 指定路徑

在class 上添加注解@WebFilter(urlPatterns={"/app/online"})

然后在啟動(dòng)類(**Application.java )上添加注解@ServletComponentScan

即可。

代碼如下:

2、 過(guò)濾所有路徑

在class上添加@Component或@Configuration 即可

如果添加了@Component或@Configuration,又添加了@WebFilter(),那么會(huì)初始化兩次Filter,并且會(huì)過(guò)濾所有路徑+自己指定的路徑 ,便會(huì)出現(xiàn)對(duì)沒(méi)有指定的URL也會(huì)進(jìn)行過(guò)濾

//過(guò)濾所有路徑
@Component
public class WebFilter implements Filter(){
//override三個(gè)方法
。。。
。。。
@Override
 public void init (FilterConfig filterConfig) throws ServletException{
 System.out.println("初始化filter");
 }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論