过滤器简介
过滤器执行流程
过滤器配置使用方式一
@Order(1) // 指定过滤器的执行顺序 @WebFilter(filterName = "CostTimeFilter", urlPatterns = "/*" , initParams = { @WebInitParam(name = "URL", value = "http://localhost:8080")}) public class CostTimeFilter implements Filter { private String url; /** * filter对象只会创建一次,init方法也只会执行一次。 */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.url = filterConfig.getInitParameter("URL"); System.out.println("Filter init..."); } /** * 主要的业务代码编写方法 */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); System.out.println(start + " Filter doFilter before..."); filterChain.doFilter(servletRequest, servletResponse); long end = System.currentTimeMillis(); System.out.println(end + "Filter doFilter after..."); } /** * 在销毁Filter时自动调用。 */ @Override public void destroy() { System.out.println("Filter destroy..."); } }
@RestController public class IndexContoller { @RequestMapping("/query") public void query() throws Exception { System.out.println("IndexContoller query..."); } }
@SpringBootApplication @ServletComponentScan // 扫描 Servlet 相关的组件 public class SpringBootFilterApplication { public static void main(String[] args) { SpringApplication.run(SpringBootFilterApplication.class, args); } }
过滤器配置方式二
public class CostTimeFilter implements Filter { private String url; /** * filter对象只会创建一次,init方法也只会执行一次。 */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.url = filterConfig.getInitParameter("URL"); System.out.println("Filter init..."); } /** * 主要的业务代码编写方法 */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); System.out.println(start + " Filter doFilter before..."); filterChain.doFilter(servletRequest, servletResponse); long end = System.currentTimeMillis(); System.out.println(end + "Filter doFilter after..."); } /** * 在销毁Filter时自动调用。 */ @Override public void destroy() { System.out.println("Filter destroy..."); } }
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean registFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new CostTimeFilter()); registration.addUrlPatterns("/*"); registration.setName("CostTimeFilter"); registration.setOrder(1); return registration; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。