SpringBoot中使用過濾器Filter-方式二
阿新 • • 發佈:2018-12-10
本篇通過配置類實現SpringBoot中是用Filter,依舊複用Servlet中的程式碼。
一、新建一個fiter類實現Filter介面:
package cn.com.winson.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest;import javax.servlet.ServletResponse; public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throwsIOException, ServletException { System.out.println("進入filter過濾器,請求正常,放行!"); chain.doFilter(request, response); } @Override public void destroy() { } }
二、配置類中配置過濾器規則:
package cn.com.winson.config; import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import cn.com.winson.filter.MyFilter; import cn.com.winson.servlet.MyServlet; /*SpringBoot沒有xml,@Configuration註解可以表示一個spring的xml配置檔案*/ @Configuration public class ServletConfig { /* * @Bean註解:相當於Spring中的配置檔案中的<bean>標籤,下面的方法相當於如下配置:id為方法名,class為返回值 <bean * id="myServletRegistrationBean" * class="org.springframework.boot.web.servlet.ServletRegistrationBean;"> * </bean> */ @Bean public ServletRegistrationBean myServletRegistrationBean() { /* 將Servlet註冊為一個bean,設定訪問路徑 */ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet"); return registrationBean; } @Bean public FilterRegistrationBean myFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter()); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } }
三、執行程式,訪問結果:
四、控制檯列印結果,包含字串:證明過濾器生效了。
總結
一、方式方法同SpringBoot中使用Servlet。