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/**是不能能生效的;