1. 程式人生 > >springboot 過濾器實現的具體步驟

springboot 過濾器實現的具體步驟

過濾器,顧名思義,能夠過濾一切請求(而攔截器只能過濾action請求),包括靜態資源的請求。

實現很簡單:

(1)寫一個過濾器。過濾實現在doFilter方法裡面。chain.doFilter(request, response)  表示過濾通過,能夠往下執行。所以過濾操作要寫在chain.doFilter(request, response) 前面,作一些條件判斷,如果不符合條件,則不執行chain.doFilter(request, response);

@WebFilter(filterName="myFilter",urlPatterns="/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.out.println("MyFilter init............");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("MyFilter doFilter.........before");
        chain.doFilter(request, response);
        System.out.println("MyFilter doFilter.........after");
    }
    @Override
    public void destroy() {
        System.out.println("MyFilter destroy..........");
    }
}
(2)別忘了讓springboot啟動類掃描servlet元件,否則是不生效的,掃描的註解是@ServletComponentScan。
@SpringBootApplication
@ServletComponentScan
public class SpringbootCompanyApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringbootCompanyApplication.class, args);
	}
}
完成。