您好,登錄后才能下訂單哦!
本篇文章為大家展示了SpringBoot中如何配置過濾器,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
使用@WebFilter注解為聲明當前類為filter,第一個參數為該filter起一個名字,第二個參數為說明要攔截的請求地址,當前類需要實現Filter接口,里面有三個方法,分別為過濾器初始化、過濾方法和過濾器銷毀。
@Slf4j@WebFilter(filterName = "myFilter1", urlPatterns = "/*")public class MyFilter1 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info(filterConfig.getFilterName() + " init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { log.info("myFilter1 begin"); try { log.info("業務方法執行"); chain.doFilter(request, response); } catch (Exception e) { log.error("error!", e); } log.info("myFilter1 end"); } @Override public void destroy() { }}
啟動類添加@ServletComponentScan注解,@ServletComponentScan注解所掃描的包路徑必須包含該Filter,代碼如下:
@SpringBootApplication@ServletComponentScan(basePackages = "com.example.demo.filter")public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
新建MyFilter2.java類,不要加注解@WebFilter,代碼如下:
@Slf4jpublic class MyFilter2 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info(filterConfig.getFilterName() + " init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { log.info("myFilter2 begin"); try { log.info("業務方法執行"); chain.doFilter(request, response); } catch (Exception e) { log.error("error!", e); } log.info("myFilter2 end"); } @Override public void destroy() { }}
新建配置類WebConfig.java,配置bean,代碼如下:
@Configurationpublic class WebConfig { @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter2()); registration.addUrlPatterns("/test"); // registration.setName("myFilter2"); return registration; }}
項目啟動后瀏覽器訪問http://localhost:8080/test,可以看到過濾器已生效,后臺打印日志如下:
[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : myFilter1 begin[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : 業務方法執行[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : myFilter1 end
上述內容就是SpringBoot中如何配置過濾器,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。