zoukankan      html  css  js  c++  java
  • 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吧 






  • 相关阅读:
    如何将应用安装到/system/app下
    WPF Perf: RenderCapability.Tier & DesiredFrameRate
    DataGridComboBoxColumn为什么就不能在Binding的时候引用其他Named Element了呢?
    A366T使用技巧
    在XAML里面引用枚举值的注意点
    高斯消元bzoj1013球形空间产生器
    欧拉函数bzoj2818简单推导
    链剖进阶ing填坑NOIP2013货车运输
    .net 2.0 BackgroundWorker 文章三篇
    19号晚21号上午
  • 原文地址:https://www.cnblogs.com/weiyuanquyu/p/8609142.html
Copyright © 2011-2022 走看看