1. 程式人生 > >filter一個請求過濾兩次地問題~

filter一個請求過濾兩次地問題~

當寫一個簡單地過濾器,做一個輸出請求uri地內容時候,會出現列印兩次...如果有邏輯,那麼也會執行兩次.到底咋回事呢;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //  userAction.setName("過濾器");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        System.out.println(req.getRequestURL());
        filterChain.doFilter(servletRequest, servletResponse);
    }
     @Bean
    public FilterRegistrationBean filterRegistrationBean(MyFilter myFilter) {
        FilterRegistrationBean f = new FilterRegistrationBean();
        f.setFilter(myFilter);
        f.addUrlPatterns("/*");
        f.setOrder(1);
        return f;
    }

列印的結果:

http://localhost:8080/get
http://localhost:8080/favicon.ico

很明顯,因為瀏覽器自己主動的又請求了一次圖示靜態資源,所以過濾器又攔截了一次;親測360,chrome,火狐都會,當然是在favicon.ico沒有快取的情況下,ie此時沒有出現...但是相應的他網頁左上角是黑的,沒有圖示....蛋疼;

知道原因了,也就能規避了,可以在攔截器中判斷請求路徑做處理;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //  userAction.setName("過濾器");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String requestURI = req.getRequestURI();
        if (requestURI.contains("favicon.ico")) {
            return;
        }
        System.out.println(req.getRequestURL());
        filterChain.doFilter(servletRequest, servletResponse);
    }