标签:etc stc oca lte des time rgs mamicode rest
@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;
}
}
标签:etc stc oca lte des time rgs mamicode rest
原文地址:https://www.cnblogs.com/danhuang/p/12769298.html