前言
傳統的javaEE增加Filter是在web.xml中配置,如以下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
|
< 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中很明顯不能這樣實現,那怎么辦呢?看完下面的教程,答案自然知道了。
老方法(新方法請直接下拉)
1.創建自定義Filter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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中增加一個@bean
1
2
3
4
5
6
7
8
9
10
11
|
@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.啟動項目
你會看到控制臺打印如下代碼:
4.訪問項目
最后我們訪問以下http://127.0.0.1:8080/test
如果你看到控制臺打印出:TestFilter
恭喜你,配置成功!
2017-04-20 最新spring-boot增加Filter方法
首先定義一個Filter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Order ( 1 ) //重點 @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() { } } |
比較核心的代碼是自定義類上面加上@WebFilter,其中@Order注解表示執行過濾順序,值越小,越先執行
我們在spring-boot的入口處加上如下注解@ServletComponentScan:
1
2
3
4
5
6
7
8
9
|
@SpringBootApplication (scanBasePackages = "com.cppba" ) //重點 @ServletComponentScan public class Application { public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(Application. class ); Environment environment = app.run(args).getEnvironment(); } } |
這種方法效果和上面版本一樣,但是用起來更加方便!以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/05c8be17c80a