springboot @WebFilter过滤器的使用
过滤器的用法就不多说了
新建Filter的继承类:MemberFilter(放置包需要注意)
@WebFilter(urlPatterns = "/*") @Order(1) public class MemberFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.err.println("自定义过滤器MemberFilter->doFilter"); } @Override public void destroy() { } }
配合@order使用,生命排序。
过滤器不在启动类扫描范围时,需要注意的是在启动类需要添加@ServletComponentScan扫描,其中包名自定义
@ServletComponentScan(basePackages = {"com.example.controller.filter"})
使用bean的情况下,jar打包是可以直接@Autowired使用的,转换war打包方式部署,获取的bean为null,这时候只能手动添加了
新建@Configuration注解类:FilterRegistrationConfig
@Configuration public class FilterRegistrationConfig { @Bean public MemberFilter memberFilter() { return new MemberFilter(); } @Bean public FilterRegistrationBean filterProxy() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); DelegatingFilterProxy httpBasicFilter = new DelegatingFilterProxy(); registrationBean.setFilter(httpBasicFilter); Map<String, String> m = new HashMap<String, String>(); m.put("targetBeanName", "memberFilter"); m.put("targetFilterLifecycle", "true"); registrationBean.setInitParameters(m); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*"); registrationBean.setUrlPatterns(urlPatterns); return registrationBean; } }
这时候还需要注意假若使用了shiro,况且上述注册的过滤器有使用到的情况下,shiroFiler的过滤必须定义在前(解决shiro报错找不到原因)
@Bean public FilterRegistrationBean delegatingFilterProxy() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); DelegatingFilterProxy proxy = new DelegatingFilterProxy(); proxy.setTargetFilterLifecycle(true); proxy.setTargetBeanName("shiroFilter"); filterRegistrationBean.setFilter(proxy); return filterRegistrationBean; }