首先定義一個統一存取 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; } }</string></string>
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中文網其他相關文章!