SpringBoot2.x攔截器的寫法:
自定義攔截器繼承HandlerInterceptorAdapter
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 攔截代碼
System.out.println("請求已經被攔截");
return true;
}
}
寫一個類實現WebMvcConfiguration,重寫addInterceptors方法
添加自定義的攔截器(addInterceptor);
配置需要攔截的請求(addPathPatterns);
配置排除攔截的請求(excludePathPatterns);
import com.sunruofei.gmall.interceptors.AuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Resource
AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/error","/bootstrap/**","/css/**","/image/**","/img/**","/js/**","/scss/**");
}
}
注意:需要排除攔截的靜態資源路徑是static下面的目錄,試過直接用/static/**是不能能生效的;