定义自定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserLoginIgnore {
boolean ignore() default true;
}
解读:
-
@Target({ElementType.METHOD}):用于指定注解的应用目标。在这里,它表示该自定义注解 @UserLoginIgnore只能用于方法上,也就是该注解只能标记方法。
-
@Retention(RetentionPolicy.RUNTIME):用于指定注解的保留策略。RetentionPolicy.RUNTIME表示该注解会在运行时保留,允许通过反射获取注解信息。
-
@Documented:这是一个标记注解,它本身不带任何属性,但用于指示编译工具要将注解信息包含在生成的文档中。
-
boolean ignore() default true;:这是自定义注解的一个属性 ignore,它是一个布尔类型的属性,默认值为 true。在注解中,属性可以用于配置注解的行为。在这个注解中,ignore 属性用于控制是否忽略Token验证,如果 ignore的值为 true,表示忽略Token验证;如果 ignore 的值为 false,表示不忽略Token验证。
添加token拦截器
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//处理跨域问题
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
return true;
}
//拦截Token
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
UserLoginIgnore userLoginIgnore = h.getMethodAnnotation(UserLoginIgnore.class);
//查看是否有@userLoginIgnore注解,若没有该注解或该注解的ignore为false,则需要token校验
if (userLoginIgnore == null || !userLoginIgnore.ignore()) {
//Token检验
//业务代码略
}
}
return true;
} else {
response.setStatus(403);
response.setContentType("application/json;charset=utf-8");
response.getWriter().println(JSONObject.toJSONString(ResultUtil.error(403, "此路径禁止访问!")));
}
return false;
}
}
其中对于拦截token部分,handler是一个方法参数,通常在SpringMVC表示controller的方法,通过方法参数获取注解,若获取到了@UserLoginIgnore注解,且ignore值为true,则进行token校验,否则不进行token校验,直接放行。
别忘了在WebMvcConfig注册拦截器。
registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/api/**");
应用
新建一个ApiController,将对外暴露的接口提取出来,加上@UserLoginIgnore注解即可。
@RestController
@RequestMapping(value = "/api/external", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class ApiController {
//对外暴露的接口
@UserLoginIgnore
@RequestMapping("/test")
public Result test() {
//业务略
}
}