SpringBoot快速使用拦截器
编写配置类WebConfig
/**
* 添加@Configuration注解将配置类交于springboot托管
*/
@Configuration
//实现WebMvcConfigurer接口
public class WebConfig implements WebMvcConfigurer {
//重写addInterceptors方法
@Override
public void addInterceptors(InterceptorRegistry registry) {
/*
registry.addInterceptor(你的拦截器).addPathPatterns("/**","这里是拦截路径可以设置多个参数,/**是对所有路径进行拦截").excludePathPatterns("这里是排除拦截的路径");
*/
registry.addInterceptor(tokenInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}
编写拦截器TokenInterceptor
/**
* 继承拦截器适配器HandlerInterceptorAdapter
*/
public class TokenInterceptor extends HandlerInterceptorAdapter {
/**
* 重写HandlerInterceptorAdapter中的preHandle方法
* preHandle:在方法被调用前执行。在该方法中可以做类似校验的功能。如果
* 返回true,则继续调用下一个拦截器。如果返回false,则中断执行,也就是
* 说我们想调用的方法 不会被执行,但是你可以修改response为你想要的响
* 应。
* postHandle:在方法执行后调用。
* afterCompletion:在整个请求处理完毕后进行回调,也就是说视图渲染完毕
* 或者调用方已经拿到响应。
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws SignatureException {
//返回true表示不拦截,返回false表示拦截
return true;
}
}