一、创建自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface 不用鉴权 {
String value();
int 单个变量() default 1;
String[] 数组() default {};
}
@interface 这种返回类型,表示这个东西是自定义注解
@Targe 指定注解可以放在哪里,HETHOD是方法上,TYPE是类、接口、枚举上。也可不写,就什么地方都能放。
@Retention 指定注解什么时候被删掉,编译时还是class加载时,RUNTIME表示运行时还存在,活最久。不知道写哪个,就用RUNTIME。
定义体内可以添加注解的值。
二、创建自定义拦截器
(1)继承了 HandlerInterceptorAdapter 类,就是一个拦截器了。
preHandle 是方法调用之前,会被执行的代码,返回false会跳过方法的执行。
/**
* 鉴权拦截处理类
*/
@Component
public class 鉴权拦截器 extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Boolean 是否登陆成功 = false;
Boolean 是否拥有权限 = false;
try{
HandlerMethod handlerMethod = (HandlerMethod)handler;
// -- 过滤不需要鉴权的api
// -- -- (1)不需要登录和权限
// 获取控制器和方法上的注解
不用鉴权 控制器上的注解 = handlerMethod.getBean().getClass().getDeclaredAnnotation(不用鉴权.class);
不用鉴权 方法上的注解 = handlerMethod.getMethod().getDeclaredAnnotation(不用鉴权.class);
if(控制器上的注解 != null || 方法上的注解 != null){
是否登陆成功 = true;
是否拥有权限 = true;
}
}catch (Exception e){
// logger.error("鉴权中出错",e);
}
if(是否登陆成功 && 是否拥有权限){
return true;
}else{
// returnJson(response,"鉴权未通过");
return false;
}
}
}
(2)注册自定义的拦截器,让spring知道何时何地调用这个拦截器。
@Configuration 表示会自动new一个实例给spring,让spring可以调用这里的代码。
继承了 WebMvcConfigurationSupport 类,表示spring在做 WebMvc 配置时,会使用这里自定义的代码。
import com.example.demo.interceptor.鉴权拦截器;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
// 让bean提前加载,让拦截器中的@Autowired生效
@Bean
public HandlerInterceptor get鉴权拦截器() {
return new 鉴权拦截器();
}
/**
* 可定义多个拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 定义过滤拦截的url名称, /** 拦截所有请求
registry.addInterceptor(this.get鉴权拦截器()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
三、完整代码
maven项目: