首先需要自定义注释
@Target(ElementType.METHOD)//使用地点
@Retention(RetentionPolicy.RUNTIME)//编译运行期都有效
public @interface Login {
}
拦截机制与非注解相似
public class AuthorizationInterceptor implements HandlerInterceptor {
//返回false 不会执行handler方法 和其他拦截器
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Class<?> methodClass = handler.getClass();
// class1.isAssignableFrom(class2) 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同,或是否是其超类或超接口。如果是则返回 true;否则返回 false
boolean flag = methodClass.isAssignableFrom(HandlerMethod.class);
if (flag){
Login login = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
//判断是否有注解
if (login!=null){
response.setContentType("application/json;charset=utf-8");
User user = (User) request.getSession().getAttribute("user");
if (user==null){
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(new Result(false, "未登录2!"));
out.write(result);
return false;
}
}
}
return true;
}
// handler方法执行完成后执行 前提是preHandler返回true
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
//响应视图前执行 前提是preHandler返回true
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}