java 使用注解 处理权限(springboot)

1、前端登陆,将用户信息传到后台

2、后台验证账号密码,如果账号密码信息正确,将登陆的用户信息保存到session中

3、自定义注解  注解名为 CheckLogin

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CheckLogin {

}

4、写一个拦截器,判断你的方法或者类上是否存在@CheakLogin注解,如何存在 验证账号密码是否正确

public class PermissionInterceptor extends HandlerInterceptorAdapter {


private SessionManager sessionManager;

@Autowired
public PermissionInterceptor(SessionManager sessionManager){
this.sessionManager = sessionManager;
}

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {

if (handler instanceof HandlerMethod){
HandlerMethod hm = (HandlerMethod)handler;

handleClassCheckLogin(hm);
handleMethodCheckLogin(hm);

}

return super.preHandle(request, response, handler);
}

// 这里我判断了类 或者 方法上面是否有我自定义的注解,如果有注解,就去从session中验证用户是否登陆成功
private void handleClassCheckLogin(HandlerMethod hm){

if ( AnnotationUtils.findAnnotation(hm.getBeanType(), CheckLogin.class) != null){

sessionManager.checkLogin();
}

}

private void handleMethodCheckLogin(HandlerMethod hm){

if ( hm.getMethodAnnotation(CheckLogin.class) != null){
sessionManager.checkLogin();
}

}

}

5、Springboot配置拦截器(spring mvc 直接在配置中配置就可)

/**
* web拦截器,检查是否登陆
*/



@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public SessionManager getSessionManager(){
return new SessionManager();
}


@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PermissionInterceptor(getSessionManager())).addPathPatterns("/**");
super.addInterceptors(registry);
}
}

6、ok了,在你和前端交互的那一层 类上或方法上打上cheacLogin吧 






原文地址:https://www.cnblogs.com/weiyuanquyu/p/8609142.html