@SpringBootApplication @ServletComponentScan("test.annotation.filter") public class SptringAnnotationFilterApplication { public static void main(String[] args) { SpringApplication.run(SptringAnnotationFilterApplication.class, args); } } @WebFilter( filterName="testFilter", urlPatterns={"/testRest"} ) public class SpringAnnotationFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // do something filterChain.doFilter(request, response); } @Override public void destroy() { } }SptringAnnotationFilterApplication
1. 設定@ServletComponentScan(filter的package)
SpringAnnotationFilter
1. implements javax.servlet.Filter
2. 設定@WebFilter(urlPatterns是設定哪些url要filter)
3. 改寫doFilter
這樣filter就可以生效
註:
若有多個filter時,在這邊使用Spring的@Order是沒有用的
真的要使用order的話可以參考下面第二種作法or使用package name去控制filter順序
2.使用Spring的FilterRegistrationBean
@SpringBootApplication public class SpringBeanConfigFilterApplication { public static void main(String[] args) { SpringApplication.run(SpringBeanConfigFilterApplication.class, args); } } @Configuration public class FilterConfig { @Bean public FilterRegistrationBean<Filter> registFilter() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(new SpringBeanConfigFilter()); registration.addUrlPatterns("/testRest"); registration.setOrder(2); registration.setName("testFilter"); return registration; } @Bean public FilterRegistrationBean<Filter> registFilter2() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(new SpringBeanConfigFilter2()); registration.addUrlPatterns("/testRest"); registration.setOrder(1); registration.setName("testFilter2"); return registration; } } public class SpringBeanConfigFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // do something filterChain.doFilter(request, response); } @Override public void destroy() { } } public class SpringBeanConfigFilter2 implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // do something filterChain.doFilter(request, response); } @Override public void destroy() { } }
使用Spring bean的方式去做設定
註:此設定的方式可以設定filter order
完整程式可參考https://github.com/softmenlouis/springBoot-filter.git
沒有留言:
張貼留言