Filter 过滤器 是Java EE 提供的只能处理 ServletRequest 和 ServletResponse 里的相关信息,不能处理与Spring相关的信息
package com.example.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; @Component public class DemoFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(DemoFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { logger.info("=========DemoFilter=======init=============="); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { logger.info("=========DemoFilter=======doFilter==start============"); filterChain.doFilter(servletRequest,servletResponse);//执行过滤 logger.info("=========DemoFilter=======doFilter==end============"); } @Override public void destroy() { logger.info("=========DemoFilter=======destroy=============="); } }
package com.example.config; import com.example.interceptor.DemoFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration//说明这是一个配置类 public class WebConfig { @Bean //Bean注入,相当于原本在web.xml中写配置注入类 public FilterRegistrationBean demoFilter(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean(); //在DemoFilter类上不用@Compent注入则可以用如下方法注入 DemoFilter demoFilter = new DemoFilter(); registrationBean.setFilter(demoFilter); List<String> urls = new ArrayList<>(); urls.add("/*");//对所有url起作用 registrationBean.setUrlPatterns(urls); return registrationBean; } }