SpringBoot中使用Filter

1.在傳統web項目中添加filter

<filter>
   <filter-name>TestFilter</filter-name> <!--定義filter名稱 和filter類 -->
    <filter-class>com.jiafeng.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>TestFilter</filter-name> 
  <url-pattern>/*</url-pattern>  <!--設置filter攔截路徑 -->
  <init-param>
    <param-name>paramName</param-name>  <!-- 添加初始參數 -->
    <param-value>paramValue</param-value>
  </init-param>
</filter-mapping>

2.在springboot中添加filter有兩種方式

2.1代碼註冊方式

先定義Filter類:Myfilter,而後經過FilterRegistrationBean將filter註冊到調用鏈中。web

@Configuration   //至關於spring中的<beans>標籤
public class WebConfiguration {

	@Bean   //至關於spring中<bean>標籤
	public FilterRegistrationBean<MyFilter> testFilterRegistration() {
		FilterRegistrationBean<MyFilter> registration = new FilterRegistrationBean<>();
		registration.setFilter(new MyFilter());
		registration.addUrlPatterns("/*");//配置過濾路徑
		registration.addInitParameter("paramName", "paramValue");//添加初始值
		registration.setName("myFilter");//設置filter名稱
		registration.setOrder(1);//請求中過濾器執行的前後順序,值越小越先執行
		return registration;
	}

	public class MyFilter implements Filter {

		@Override
		public void destroy() {
			System.out.println("銷燬MyFilter");
		}

		@Override
		public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
				throws IOException, ServletException {
			HttpServletRequest request = (HttpServletRequest) sRequest;
			System.out.println("this is MyFilter url :" + request.getRequestURI());
			chain.doFilter(sRequest, sResponse);
		}

		@Override
		public void init(FilterConfig arg0) throws ServletException {
			System.out.println("初始化MyFilter");
		}

	}
}

2.2註解註冊方式

定義過濾器類:HelloFilter,在過濾器類上添加@WebFilter註解配置過濾器名稱、過濾路徑等屬性,經過@Order配置過濾器執行順序。spring

注意使用@WebServlet、@WebFilter、@WebListener等servlet註解時須要在springboot的啓動類上添加@ServletComponentScan註解,不然不會生效。springboot

@WebFilter(urlPatterns="/*",filterName="helloFilter",initParams= {@WebInitParam(name="paramName",value="paramValue"),@WebInitParam(name="paramName2",value="paramValue2")})
@Order(2)
public class HelloFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		System.out.println("執行過濾器Hello Filter !");
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("初始化HelloFilter!");
	}

}

啓動類app

@SpringBootApplication
@ServletComponentScan
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
相關文章
相關標籤/搜索