SpringBoot中Filter沒(méi)有生效原因及解決方案
我的一個(gè)老項(xiàng)目從SpringMvc升級(jí)到了SpringBoot、項(xiàng)目中使用了兩個(gè)過(guò)濾器,分別是XSS注入過(guò)濾器和CSRF攻擊過(guò)濾器。
Servlet 三大組件 Servlet、Filter、Listener 在傳統(tǒng)項(xiàng)目中需要在 web.xml 中進(jìn)行相應(yīng)的配置。
Servlet 3.0 開(kāi)始在 javax.servlet.annotation 包下提供 3 個(gè)對(duì)應(yīng)的 @WebServlet、@WebFilter、@WebListener 注解來(lái)簡(jiǎn)化操作,@WebServlet、@WebFilter、@WebListener 寫在對(duì)應(yīng)的 Servlet、Filter、Listener 類上作為標(biāo)識(shí),從而不需要在 web.xml 中進(jìn)行配置了。
因此新的代碼如下
@Component @WebFilter(urlPatterns = {"/*"}, filterName = "csrfFilter") public class WebCsrfFilter implements Filter{ }
和
@Component @WebFilter(urlPatterns = {"/*"}, filterName = "xssFilter") public class WebXssFilter extends XssFilter { }
在測(cè)試過(guò)程中發(fā)現(xiàn)設(shè)置的Filter沒(méi)有生效,經(jīng)過(guò)排查發(fā)現(xiàn)需要注意的是:Spring Boot 應(yīng)用中這三個(gè)注解默認(rèn)是不被掃描的,需要在項(xiàng)目啟動(dòng)類上添加 @ServletComponentScan 注解, 表示對(duì) Servlet 組件掃描。
因此在SpringBootApplication項(xiàng)目上需要使用@ServletComponentScan注解后,Servlet、Filter、Listener才可以直接通過(guò)@WebServlet、@WebFilter、@WebListener注解自動(dòng)注冊(cè),無(wú)需其他代碼。
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan(basePackages = "com.web.global.filter") public class WebApplication extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); }
到此這篇關(guān)于SpringBoot中Filter沒(méi)有生效原因排查的文章就介紹到這了,更多相關(guān)SpringBoot中Filter沒(méi)有生效內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis單個(gè)參數(shù)的if判斷報(bào)異常There is no getter for property named ''x
今天小編就為大家分享一篇關(guān)于Mybatis單個(gè)參數(shù)的if判斷報(bào)異常There is no getter for property named 'xxx' in 'class java.lang.Integer'的解決方案,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12Java實(shí)戰(zhàn)之多線程模擬站點(diǎn)售票
今天帶大家來(lái)練習(xí)Java實(shí)戰(zhàn),文中多線程模擬站點(diǎn)售票這個(gè)問(wèn)題作了詳細(xì)的介紹,對(duì)正在學(xué)習(xí)java的小伙伴們有很好地幫助,需要的朋友可以參考下2021-05-05SWT(JFace)體驗(yàn)之Slider,Scale
SWT(JFace)體驗(yàn)之Slider,Scale實(shí)現(xiàn)代碼。2009-06-06詳解基于Spring Boot與Spring Data JPA的多數(shù)據(jù)源配置
本篇文章主要介紹了詳解基于Spring Boot與Spring Data JPA的多數(shù)據(jù)源配置,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05mybatis向數(shù)據(jù)庫(kù)里插入記錄后自動(dòng)返回記錄ID問(wèn)題
本文介紹了在接手項(xiàng)目時(shí),對(duì)一個(gè)業(yè)務(wù)處理邏輯進(jìn)行重構(gòu)和性能優(yōu)化的經(jīng)歷,作者提到,性能問(wèn)題可能是導(dǎo)致bug的一個(gè)重要原因,作者提到,在以前的.NET項(xiàng)目中,插入記錄后系統(tǒng)會(huì)自動(dòng)刷新實(shí)體類,為其中的主鍵ID賦值,而SpringBoot項(xiàng)目mybatis也可以通過(guò)指定主鍵來(lái)優(yōu)化代碼2025-01-01