首先定义一个统一访问 URL 拦截的 Filter。代码如下:
public class UrlFilter implements Filter { private Logger log = LoggerFactory.getLogger(UrlFilter.class); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String requestURI = httpServletRequest.getRequestURI(); StringBuffer requestURL = httpServletRequest.getRequestURL(); log.info("requestURI:" +requestURI+" "+"requestURL:"+requestURL); chain.doFilter(httpServletRequest, response); } }
通过 javaConfig方式配置 SpringBoot 过滤链类 FilterRegistrationBean,具体代码如下:
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean filterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new UrlFilter()); List<String> urlList = new ArrayList<String>(); urlList.add("/*"); registration.setUrlPatterns(urlList); registration.setName("UrlFilter"); registration.setOrder(1); return registration; } }
FilterRegistrationBean 中方法介绍:
registration.setFilter(Filter filter):设置我们自定义Filter对象。
registration.setUrlPatterns(Collection urlPatterns):设置自定义Filter需要拦截的URL的集合。
registration.setName(String name): 设置自定义Filter名称。
registration.setOrder(int order):设置自定义Filter拦截顺序。
测试
启动 SpirngBoot 项目并通过游览器访问我们的项目下的 index.html。
以上是怎么在SpringBoot2中整合Filter的详细内容。更多信息请关注PHP中文网其他相关文章!