spring boot 配置攔截器要寫一個配置類和一個攔截器類。在配置類里面將攔截器注冊到spring boot 項目里,在攔截器里面實現攔截處理的方法。
先看配置類的代碼
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 后台管理配置類 */ /** * 后台管理配置類 */ @Configuration public class AdminConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //注冊TestInterceptor攔截器 InterceptorRegistration registration = registry.addInterceptor(adminInterceptor()); registration.addPathPatterns("/sys/**"); //所有sys路徑都被攔截 // registration.excludePathPatterns( //添加不攔截路徑 // "你的登陸路徑", //登錄 // "/**/*.html", //html靜態資源 // "/**/*.js", //js靜態資源 // "/**/*.css", //css靜態資源 // "/**/*.woff", // "/**/*.ttf" // ); }@Bean //將自定義攔截器注冊到spring bean中
public AdminInterceptor adminInterceptor(){
return new AdminInterceptor();
}
}
攔截器類
public class AdminInterceptor implements HandlerInterceptor {
//重寫方法
}