過濾器(Filter)是Servlet中經常使用的技術,能夠實現用戶在訪問某個目標資源以前,對訪問的請求和響應進行攔截,經常使用的場景有登陸校驗、權限控制、敏感詞過濾等,下面介紹下Spring Boot配置過濾器的兩種方式。css
1、@WebFilter註解方式2、@Bean註解方式3、查看運行效果html
使用@WebFilter註解爲聲明當前類爲filter,第一個參數爲該filter起一個名字,第二個參數爲說明要攔截的請求地址,當前類須要實現Filter接口,裏面有三個方法,分別爲過濾器初始化、過濾方法和過濾器銷燬。java
@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,代碼以下:git
@SpringBootApplication
@ServletComponentScan(basePackages = "com.example.demo.filter")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
新建MyFilter2.java類,不要加註解@WebFilter,代碼以下:github
@Slf4j
public 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,代碼以下:spring
@Configuration
public 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
到此Spring Boot配置過濾器的兩種方式已經所有實現,有問題歡迎留言溝通哦!
完整源碼地址: https://github.com/suisui2019/springboot-studyspringboot
推薦閱讀微信
1.Spring Boot統一異常處理實戰
2.從技術的角度分析下爲何不要在網上發「原圖」
3.利用Spring Boot+zxing,生成二維碼還能這麼簡單
4.Spring Boot之Profile--快速搞定多環境使用與切換
5.利用Spring Boot+WxJava實現網站集成微信登陸功能併發
Java碎碎念公衆號限時領取免費Java相關資料,涵蓋了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高併發分佈式、大數據、機器學習等技術。
關注下方公衆號便可免費領取:
原文出處:https://www.cnblogs.com/haha12/p/11472582.html