在 Spring Boot 中,配置攔截器需要繼承 HandlerInterceptorAdapter 類,并重寫其中的 preHandle()、postHandle()、afterCompletion() 等方法。下面是一個(gè)詳細(xì)的實(shí)例: 首先,我們創(chuàng)建一個(gè)攔截器類 MyInterceptor,繼承 HandlerInterceptorAdapter 類,并在其中重寫 preHandle() 方法:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("請(qǐng)求處理前執(zhí)行");
return true;
}
}
其中,preHandle() 方法用于在請(qǐng)求處理前執(zhí)行,這里我們簡(jiǎn)單地輸出一句話。 然后,我們需要在配置類中注冊(cè)攔截器。在 Spring Boot 中,我們可以通過(guò)實(shí)現(xiàn) WebMvcConfigurer 接口,并重寫 addInterceptors() 方法來(lái)配置攔截器。下面是一個(gè)示例:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-536618.html
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login");
}
}
在上面的代碼中,我們通過(guò)實(shí)現(xiàn) WebMvcConfigurer 接口,并重寫 addInterceptors() 方法來(lái)注冊(cè)攔截器。其中,addInterceptor() 方法用于注冊(cè)攔截器,addPathPatterns() 方法用于指定攔截的 URL 路徑模式,excludePathPatterns() 方法用于指定不攔截的 URL 路徑模式。 在上面的示例中,我們注冊(cè)了 MyInterceptor 攔截器,并指定了攔截所有 URL 路徑模式,但排除了 /login 路徑模式。 需要注意的是,在 Spring Boot 中,如果我們同時(shí)使用了 WebMvcConfigurer 和 WebFluxConfigurer 接口來(lái)配置 MVC 和 WebFlux,那么需要在配置類上添加 @EnableWebMvc 或 @EnableWebFlux 注解,否則只能使用其中一個(gè)接口來(lái)配置 MVC 或 WebFlux。 綜上所述,我們可以通過(guò)實(shí)現(xiàn) WebMvcConfigurer 接口,并重寫 addInterceptors() 方法來(lái)配置攔截器,在其中注冊(cè)攔截器并指定攔截的 URL 路徑模式和不攔截的 URL 路徑模式。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-536618.html
到了這里,關(guān)于Springboot如何配置攔截器的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!