在springboot中如何使用filter設(shè)置要排除的URL
使用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進入的方法");
chain.doFilter(req, res);
}
else {
System.out.println("這里是需要處理的url進入的方法");
}
}
@Override
public void destroy() {
System.out.println("destroy----------filter");
}
}
@Order中的value越小,優(yōu)先級越高。
ALLOWED_PATHS
這個是一個集合,存放的是需要排出的URL,用來判斷是否是需要排除的URL。
關(guān)于為什么SpringBoot中使用了@WebFilter但是過濾器卻沒有生效:一定要加上@Configuration注解,@Service其實也可以,其他類似。
filter指定過濾URL的常見問題
在使用Filter對一些自己指定的URL進行過濾攔截時
經(jīng)常會出現(xiàn)如下錯誤
1、 明明在@WebFilter(urlPatterns={"/app/online"})中過濾的是/app/online 路徑,但是運行之后發(fā)現(xiàn),這個WebFilter過濾器對所有的URL都進行了過濾。
2、 運行之后發(fā)現(xiàn)過濾器沒有初始化,沒有被加載
下面總結(jié)一下使用正確的
合適的注解配置filter的方法:
1、 指定路徑
在class 上添加注解@WebFilter(urlPatterns={"/app/online"})
然后在啟動類(**Application.java )上添加注解@ServletComponentScan
即可。
代碼如下:


2、 過濾所有路徑
在class上添加@Component或@Configuration 即可
如果添加了@Component或@Configuration,又添加了@WebFilter(),那么會初始化兩次Filter,并且會過濾所有路徑+自己指定的路徑 ,便會出現(xiàn)對沒有指定的URL也會進行過濾
//過濾所有路徑
@Component
public class WebFilter implements Filter(){
//override三個方法
。。。
。。。
@Override
public void init (FilterConfig filterConfig) throws ServletException{
System.out.println("初始化filter");
}
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java基礎(chǔ)之內(nèi)部類與代理知識總結(jié)
今天帶大家復(fù)習(xí)Java的基礎(chǔ)知識,文中有非常詳細的介紹及圖文示例,對正在學(xué)習(xí)Java的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06
String轉(zhuǎn)BigDecimal,BigDecimal常用操作,以及避免踩坑記錄
這篇文章主要介紹了String轉(zhuǎn)BigDecimal,BigDecimal常用操作,以及避免踩坑記錄,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
springboot使用redis對單個對象進行自動緩存更新刪除的實現(xiàn)
本文主要介紹了springboot使用redis對單個對象進行自動緩存更新刪除的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
SSH框架網(wǎng)上商城項目第13戰(zhàn)之Struts2文件上傳功能
這篇文章主要為大家詳細介紹了SSH框架網(wǎng)上商城項目第13戰(zhàn)之Struts2文件上傳功能的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-06-06

