Spring Boot —— Filter 过滤器
目标
实现一个自定义过滤器,在所有请求进来时输出点儿信息
实现过滤器
实现一个自定义过滤器,在所有请求进行业务处理前,在控制台输出请求Id和请求Url
@Configuration
@EnableWebMvc
public class WebConfiguration {
public static class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println(STR."RequestId: \{request.getRequestId()},请求方式:\{request.getRequestURI()}");
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
注册过滤器
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<WebConfiguration.MyFilter> myFilterFilterRegistrationBean(){
FilterRegistrationBean<WebConfiguration.MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new WebConfiguration.MyFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setName("myFilter");
return filterRegistrationBean;
}
}