您好,登錄后才能下訂單哦!
在spring-boot項(xiàng)目中如何實(shí)現(xiàn)自定義filter?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
傳統(tǒng)的javaEE增加Filter是在web.xml中配置,如以下代碼:
<filter> <filter-name>TestFilter</filter-name> <filter-class>com.cppba.filter.TestFilter</filter-class> </filter> <filter-mapping> <filter-name>TestFilter</filter-name> <url-pattern>/*</url-pattern> <init-param> <param-name>paramName</param-name> <param-value>paramValue</param-value> </init-param> </filter-mapping>
然而spring-boot中很明顯不能這樣實(shí)現(xiàn),那怎么辦呢?看完下面的教程,答案自然知道了。
老方法(新方法請(qǐng)直接下拉)
1.創(chuàng)建自定義Filter
package com.cppba.filter; import javax.servlet.*; import java.io.IOException; public class TestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("TestFilter"); } @Override public void destroy() { } }
2.在ApplicationConfiguration.java中增加一個(gè)@bean
@Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new TestFilter()); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("testFilter"); registration.setOrder(1); return registration; }
3.啟動(dòng)項(xiàng)目
你會(huì)看到控制臺(tái)打印如下代碼:
4.訪問(wèn)項(xiàng)目
最后我們?cè)L問(wèn)以下http://127.0.0.1:8080/test
如果你看到控制臺(tái)打印出:TestFilter
恭喜你,配置成功!
2017-04-20 最新spring-boot增加Filter方法
首先定義一個(gè)Filter
@Order(1) //重點(diǎn) @WebFilter(filterName = "testFilter1", urlPatterns = "/*") public class TestFilterFirst implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("TestFilter1"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
比較核心的代碼是自定義類(lèi)上面加上@WebFilter,其中@Order注解表示執(zhí)行過(guò)濾順序,值越小,越先執(zhí)行
我們?cè)趕pring-boot的入口處加上如下注解@ServletComponentScan:
@SpringBootApplication(scanBasePackages = "com.cppba") //重點(diǎn) @ServletComponentScan public class Application { public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(Application.class); Environment environment = app.run(args).getEnvironment(); } }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。