Java之Filter - Zh1z3ven - 博客园 (cnblogs.com)
package io.veal.filter; import javax.servlet.*; import java.io.IOException; public class FilterA implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{ System.out.println("\033[37;7m" + "FilterA pre" + "\033[0m"); chain.doFilter(request, response); System.out.println("\033[37;7m" + "FilterA post" + "\033[0m"); } @Override public void init(FilterConfig filterConfig) throws ServletException{ System.out.println("\033[37;7m" + "FilterA init" + "\033[0m"); String param = filterConfig.getInitParameter("param"); // init方法中, 读取init-param System.out.println("FilterA init Method param = " + param); Filter.super.init(filterConfig); } @Override public void destroy(){ System.out.println("\033[37;7m" + "FilterA destroy" + "\033[0m"); Filter.super.destroy(); } }
package io.veal.filter; import javax.servlet.*; import java.io.IOException; public class FilterB implements Filter{ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{ System.out.println("\033[37;7m" + "FilterB pre" + "\033[0m"); chain.doFilter(request, response); System.out.println("\033[37;7m" + "FilterB post" + "\033[0m"); } @Override public void init(FilterConfig filterConfig) throws ServletException{ System.out.println("\033[37;7m" + "FilterB init" + "\033[0m"); Filter.super.init(filterConfig); } @Override public void destroy(){ System.out.println("\033[37;7m" + "FilterB destroy" + "\033[0m"); Filter.super.destroy(); } }
package io.veal.config; import io.veal.filter.FilterA; import io.veal.filter.FilterB; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig{ @Bean public FilterRegistrationBean<FilterA> filterA(){ FilterRegistrationBean<FilterA> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setName("FilterA"); filterRegistrationBean.setFilter(new FilterA()); filterRegistrationBean.addUrlPatterns("/servlet/category/*"); // 不能加context-path, 使用 * filterRegistrationBean.setOrder(Integer.MAX_VALUE - 100); // 数字越小,优先级越高 filterRegistrationBean.addInitParameter("param", "value"); filterRegistrationBean.setEnabled(true); return filterRegistrationBean; } @Bean public FilterRegistrationBean<FilterB> filterB(){ FilterRegistrationBean<FilterB> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setName("FilterB"); filterRegistrationBean.setFilter(new FilterB()); filterRegistrationBean.addUrlPatterns("/servlet/category/*"); // 不能加context-path, 使用 * filterRegistrationBean.setOrder(Integer.MAX_VALUE - 1000); // 数字越小,优先级越高 filterRegistrationBean.setEnabled(true); return filterRegistrationBean; } }