一、基于URL实现的拦截器:
/**
* @description:常量类
* @author: Lxq
* @date: 2020/5/25 8:58
*/
public class Const {
/**
* 不验证URL anon:不验证/authc:受控制的
*/
public static final String NO_INTERCEPTOR_PATH = ".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}
/**
* @description: 基于URL实现拦截器
* @author: Lxq
* @date: 2020/5/25 8:41
*/
public class LoginInterceptor extends HandlerInterceptorAdapter {
/**
* 在请求之前调用
* 基于URL实现的拦截器
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 请求头中是否带token
String token = request.getHeader("token");
String path = request.getServletPath();
if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
// 不需要过滤的请求
return true;
}else {
// 拦截器要做的是,判断令牌,权限等信息
System.out.println("====================================");
return true;
}
}
}
二、基于注解的拦截器
1.创建注解
/**
* @description:在需要登录验证的Controller的方法上使用此注解
* @author: Lxq
* @date: 2020/5/25 9:22
*/
@Target({ElementType.METHOD})// 可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface LoginRequired {
}
2.创建拦截器
/**
* @description: 基于注解的拦截器
* @author: Lxq
* @date: 2020/5/25 9:20
*/
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
// 方法注解级拦截器
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 判断接口是否需要登录
LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
// 有 @LoginRequired 注解,需要认证
if (methodAnnotation != null) {
// 这写你拦截需要做的事情,比如取缓存,SESSION,权限判断等
System.out.println("====================================");
return true;
}
return true;
}
}
三、把拦截器添加到配置中,相当于SpringMVC时的配置文件
/**
* @description: 将拦截器添加到配置中
* @author: Lxq
* @date: 2020/5/25 9:05
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
}
@Bean
public LoginInterceptor LoginInterceptor() {
return new LoginInterceptor();
}
@Bean
public AuthorityInterceptor AuthorityInterceptor() {
return new AuthorityInterceptor();
}
}