跳转至

攔截器 Interceptor

http request 如果有問題 ,直接返回錯誤的訊息給前端

http request 如果沒有問題 ,允許這個http request 可以去執行這個 url 路徑所對應的方法

練習

@RestController
public class MyController7 {
    @RequestMapping("/test")
    public String test() {
        System.out.println("執行 test 方法");
        return "Hello test1";
    }

    @RequestMapping("/test2")
    public String test2() {
        System.out.println("執行 test2 方法");
        return "Hello test2";
    }
}

主要還是 preHandle 這個方法 boolean 回傳的值結果代表 攔截器是否拒絕讓這個 http request 通過

實作了 HandlerInterceptor 這個介面後 ,MyInterceptor就變成是一個攔截器

當一個 http request 進來的時候 ,Spring Boot 首先會去執行攔截器的 preHandle() 方法 ,去判斷說這個 http request 是否有問題

@Component
public class MyInterceptor implements HandlerInterceptor{
    // 實作了 HandlerInterceptor 這個介面後 ,MyInterceptor就變成是一個攔截器
    // 當一個 http request 進來的時候 ,Spring Boot 首先會去執行攔截器的 preHandle() 方法 ,去判斷說這個 http request 是否有問題 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("執行 MyInterceptor 的 preHandle 方法");
        return true;
    }
}
@Configuration
public class MyConfig implements WebMvcConfigurer{

    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }

}

Talend API Tester

GET http://localhost:8080/test

console:

執行 MyInterceptor 的 preHandle 方法
執行 test 方法

定義回傳的http 狀態碼

response.setStatus(401);

@Component
public class MyInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("執行 MyInterceptor 的 preHandle 方法");
        response.setStatus(401);
        return true;
    }
}