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