前言
以往的javaEE增加Filter是在web.xml中配置肺蔚,然而spring-boot中很明顯不能這樣實(shí)現(xiàn)溪窒,那怎么辦呢夯接?看完下面的教程闲擦,答案自然知道了慢味。
開(kāi)源地址:https://github.com/bigbeef
個(gè)人博客:http://blog.cppba.com
前言
傳統(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)打印如下代碼:
https://github.com/bigbeef/cppba-spring-boot
4.訪問(wèn)項(xiàng)目
最后我們?cè)L問(wèn)以下http://127.0.0.1:8080/test
如果你看到控制臺(tái)打印出:TestFilter
https://github.com/bigbeef/cppba-spring-boot
恭喜你驰唬,配置成功顶岸!
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();
}
}
這種方法效果和上面版本一樣,但是用起來(lái)更加方便搓逾!