首頁 > 軟體

SpringBoot使用Interceptor攔截器的範例

2023-03-19 06:03:12

在springboot中使用攔截器也比較簡單,實現HandlerInterceptor或者AsyncHandlerInterceptor介面,再從設定裡新增一下攔截器就完成了;

AsyncHandlerInterceptor介面繼承了HandlerInterceptor,多了一個afterConcurrentHandlingStarted方法:

介面裡的方法:

  • preHandle:在Controller之前執行,可以判斷引數,執行的controller方法等,返回值為boolean,返回true繼續往下執行(下面的攔截器和controller),否則開始返回操作(執行之前的攔截器返回等操作);
  • postHandle:在Controller之後,檢視返回前執行,可對ModelAndView進行處理再返回;
  • afterCompletion:請求完成後執行;
  • afterConcurrentHandlingStarted:controller返回值是java.util.concurrent.Callable時才會呼叫該方法並使用新執行緒執行;

方法執行順序有兩種:

  • preHandle -> 執行Controller -> postHandle -> afterCompletion;
  • preHandle -> 執行Controller -> afterConcurrentHandlingStarted -> callable執行緒執行call()方法 -> 新執行緒開始preHandle -> postHandle -> afterCompletion;(controller方法返回Callable物件時)

設定攔截器:

實現WebMvcConfigurer介面裡的addInterceptors方法,使用引數InterceptorRegistry物件新增自己的攔截器,可以新增指定攔截路徑或者去掉某些過濾路徑,還可以設定攔截器的優先順序order,優先順序由小到大,預設0;

多個攔截器的執行順序:

preHandle方法按照order由小到大順序,執行完controller後,其他方法則反向順序,跟過濾器Filter類似;

測試啟動類,預設設定:

/**
 * 2023年3月16日下午4:56:23
 */
package testspringboot.test9interceptor;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
/**
 * @author XWF
 *
 */
@SpringBootApplication
public class Test9Main {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Test9Main.class, args);
    }
 
}

controller類:

/**
 * 2023年3月16日下午4:58:02
 */
package testspringboot.test9interceptor;
 
import java.util.concurrent.Callable;
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author XWF
 *
 */
@RestController
@RequestMapping("/interceptor")
public class Test9Controller {
 
    @RequestMapping("/a")
    public String a(String s) {
        System.out.println(">>>a():" + s);
        return "OK";
    }
    
    @RequestMapping("/b")
    public Callable<String> b() {
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                System.out.println("call() thread id=" + Thread.currentThread().getId());
                Thread.sleep(2000);
                return "abcdefg";
            }
        };
        System.out.println(">>>b()");
        return callable;
    }
    
}

兩個自定義攔截器1和2:

/**
 * 2023年3月16日下午5:14:14
 */
package testspringboot.test9interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author XWF
 *
 */
public class MyInterceptor1 implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle 1, handler=" + handler);
        return request.getQueryString().length() < 10 ? true : false; 
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 1");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("afterCompletion 1");
    }
    
}
/**
 * 2023年3月16日下午5:15:28
 */
package testspringboot.test9interceptor;
 
import java.util.Date;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
/**
 * @author XWF
 *
 */
@Component
public class MyInterceptor2 implements AsyncHandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle 2 " + new Date() + " ThreadId=" + Thread.currentThread().getId());
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle 2");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("afterCompletion 2");
    }
    
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("afterConcurrentHandlingStarted 2 " + new Date());
    }
    
}

設定攔截器:

/**
 * 2023年3月16日下午5:20:31
 */
package testspringboot.test9interceptor;
 
import javax.annotation.Resource;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * @author XWF
 *
 */
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
 
    @Resource
    MyInterceptor2 myinterceptor2;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor1())
            .addPathPatterns("/interceptor/a")        //新增攔截路徑,兩種引數List<String>和String ...
            .excludePathPatterns("/interceptor/b")        //排除路徑,兩種引數List<String>和String ...
            .order(1);        //設定攔截器順序,由小到大,預設0
        registry.addInterceptor(myinterceptor2);    //也可以使用spring管理的物件
    }
    
}

傳送一個post測試請求:http://192.168.1.30:8080/interceptor/a?s=hello,攔截器2的order預設0,攔截器1的order為1,preHandle先執行2的,controller執行之後,剩下的Handle都是先執行1再執行2的;

傳送preHandle返回false的請求:http://192.168.1.30:8080/interceptor/a?s=hello123456789,攔截器1的preHandle返回false後,直接執行2的afterCompletion;

傳送測試callable的請求:http://192.168.1.30:8080/interceptor/b?s=hello,攔截路徑設定跳過攔截器1只執行攔截器2,通過threadid可以看到前後使用的是兩個執行緒;

到此這篇關於SpringBoot使用Interceptor攔截器的文章就介紹到這了,更多相關SpringBoot使用Interceptor攔截器內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com