SpringBoot 中过滤器的简介及使用方式
2021-02-09 00:15
标签:etc stc oca lte des time rgs mamicode rest SpringBoot 中过滤器的简介及使用方式 标签:etc stc oca lte des time rgs mamicode rest 原文地址:https://www.cnblogs.com/danhuang/p/12769298.html过滤器简介
过滤器执行流程
过滤器配置使用方式一
@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;
}
}
上一篇:图相关算法c/c++
文章标题:SpringBoot 中过滤器的简介及使用方式
文章链接:http://soscw.com/index.php/essay/52864.html