ホームページ  >  記事  >  Java  >  hiroのソースコード学習におけるSession session = getSession()の解析例

hiroのソースコード学習におけるSession session = getSession()の解析例

黄舟
黄舟オリジナル
2017-07-24 13:26:517409ブラウズ

subject は、ログイン、ログアウト、ロール/権限の表示など、ユーザーがサーバーにアクセスするためのいくつかの操作を表します。

同時に、subject.getSession()、このインターフェイス、などのセッションを取得できます。セッションが以前に存在していない場合は、セッションを作成します。作成プロセスは大まかに以下のとおりです。

subjectがSecurityManagerに作成を委託し、SecurityManagerがSessionManagerに作成を委託し、SessionManagerはSessionFactoryファクトリーを通じて作成されます。 「Shiro」の制作過程における分業が明確であることがわかります。

作成プロセスは次のように分析されます。

(1)Session は DelegatingSubject クラスで取得できます:

public Session getSession(boolean create) {
      .......
      SessionContext sessionContext = createSessionContext();
      //创建Session上下文,context有个backMap,存放创建Session时所需的数据
      Session session = this.securityManager.start(sessionContext);
      this.session = decorate(session);//创建代理session,当session.stop()调用时,清空subject的session
      .......
      return this.session;//返回代理session
 }

(2)SecurityManager は sessionManager(DefaultSessionManage) にセッションの作成を処理させます:

1 public Session start(SessionContext context) throws AuthorizationException {
2     return this.sessionManager.start(context);
3     }

*注: DefaultSessionManage の内部構造は次のとおりです:

(3) AbstractNativeSessionManager がセッションを作成し、セッションを管理します:

public Session start(SessionContext context) {
        Session session = createSession(context);//通过模板模式,子类实现通过上下仍创建Session
        applyGlobalSessionTimeout(session);//更新sessionDAO的sessions(map<String,session>)
        onStart(session, context);//一个槽点,待子类实现
        notifyStart(session);//注册的监听器开始执行
        //Don&#39;t expose the EIS-tier Session object to the client-tier:
        return createExposedSession(session, context);//创建暴露的Session
    }

(4) セッションの作成が完了し、詳細なコードは次のとおりです: AbstractNativeSessionManager が処理のために AbstractValidatingSessionManager に渡されます:

protected Session createSession(SessionContext context) throws AuthorizationException {
        enableSessionValidationIfNecessary();
        //创建Session之前,先起一个Session自动定时任务的线程去执行,校验sessionDAO的sessions是否过期。
        return doCreateSession(context);
    }
//
private void enableSessionValidationIfNecessary() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (isSessionValidationSchedulerEnabled() && (scheduler == null || !scheduler.isEnabled())) {
            enableSessionValidation();
        }
    }
//
protected void enableSessionValidation() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (scheduler == null) {
            scheduler = createSessionValidationScheduler();
            //scheduler = new ExecutorServiceSessionValidationScheduler(this);scheduler.setInterval(getSessionValidationInterval());
            setSessionValidationScheduler(scheduler);
        }
        if (log.isInfoEnabled()) {
            log.info("Enabling session validation scheduler...");
        }
        scheduler.enableSessionValidation();//自动任务启动执行
        afterSessionValidationEnabled();//一个槽点,待子类实现
}

(5) ExecutorServiceSessionValidationScheduler が検証しますセッションの有効期限:

/**
     * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals 
     * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
     */
    //TODO Implement an integration test to test for jvm exit as part of the standalone example
    // (so we don&#39;t have to change the unit test execution model for the core module)
    public void enableSessionValidation() {
        if (this.interval > 0l) {
            this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {  
            public Thread newThread(Runnable r) {  
                Thread thread = new Thread(r);  
                thread.setDaemon(true);  
                return thread;  
                }  
            });                  
            this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
            this.enabled = true;
        }
    }

    public void run() {
        if (log.isDebugEnabled()) {
            log.debug("Executing session validation...");
        }
        long startTime = System.currentTimeMillis();
        this.sessionManager.validateSessions();//ExecutorServiceSessionValidationSchedule的在被SessionManager创建里,
        long stopTime = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
        }
    }

(6) AbstractValidatingSessionManager セッションの有効期限を検証します:

/**
     * @see ValidatingSessionManager#validateSessions()
     */
    public void validateSessions() {
        if (log.isInfoEnabled()) {
            log.info("Validating all active sessions...");
        }
        int invalidCount = 0;
        Collection<Session> activeSessions = getActiveSessions();//获取取保存的Session
        if (activeSessions != null && !activeSessions.isEmpty()) {
            for (Session s : activeSessions) {
                try {
                    //simulate a lookup key to satisfy the method signature.
                    //this could probably stand to be cleaned up in future versions:
                    SessionKey key = new DefaultSessionKey(s.getId());
                    validate(s, key);
                } catch (InvalidSessionException e) {
                    if (log.isDebugEnabled()) {
                        boolean expired = (e instanceof ExpiredSessionException);
                        String msg = "Invalidated session with id [" + s.getId() + "]" +
                                (expired ? " (expired)" : " (stopped)");
                        log.debug(msg);
                    }
                    invalidCount++;
                }
            }
        }

        if (log.isInfoEnabled()) {
            String msg = "Finished session validation.";
            if (invalidCount > 0) {
                msg += "  [" + invalidCount + "] sessions were stopped.";
            } else {
                msg += "  No sessions were stopped.";
            }
            log.info(msg);
        }
    }
    //类DefaultSessionManager实现getActiveSessions接口
    protected abstract Collection<Session> getActiveSessions();

     protected Collection<Session> getActiveSessions() {
        Collection<Session> active = sessionDAO.getActiveSessions();
        return active != null ? active : Collections.<Session>emptySet();
    }

(7) セッションの検証が完了すると、DefaultSessionManager がセッションを作成します:

protected Session doCreateSession(SessionContext context) {
        Session s = newSessionInstance(context);
        if (log.isTraceEnabled()) {
            log.trace("Creating session for host {}", s.getHost());
         }
        create(s);
        return s;
     }

   protected Session newSessionInstance(SessionContext context) {
      return getSessionFactory().createSession(context);
   }
   protected void create(Session session) {
      if (log.isDebugEnabled()) {
         log.debug("Creating new EIS record for new session instance [" + session + "]");
        }
      sessionDAO.create(session);
    }

(8) DefaultSessionManager はセッションを維持するためのセッション (MemorySessionDAO):

protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        storeSession(sessionId, session);
        return sessionId;
    }
        protected Session storeSession(Serializable id, Session session) {
          if (id == null) {
             throw new NullPointerException("id argument cannot be null.");
          }
          return sessions.putIfAbsent(id, session);
        }

(9) 作成および維持 セッション後、AbstractNativeSessionManager が登録されたリスナーに渡され、リスナーは onStart インターフェース

  protected void notifyStart(Session session) {
  2         for (SessionListener listener : this.listeners) {
  3             listener.onStart(session);
  4         }
  5     }

(10) を呼び出し、最後にデリゲートを作成しますSession,

protected Session createExposedSession(Session session, SessionContext context) {        
return new DelegatingSession(this, new DefaultSessionKey(session.getId()));
    }

(11) 最後に、サブジェクトは独自のプロキシ セッションを作成します。これは主に stop メソッドをインターセプトするために使用されます:

protected Session decorate(Session session) {
         if (session == null) {
             throw new IllegalArgumentException("session cannot be null");
         }
         return new StoppingAwareProxiedSession(session, this);
     }
    private class StoppingAwareProxiedSession extends ProxiedSession {

           private final DelegatingSubject owner;

           private StoppingAwareProxiedSession(Session target, DelegatingSubject owningSubject) {
                super(target);
                owner = owningSubject;
            }
16            public void stop() throws InvalidSessionException {
           super.stop();
           owner.sessionStopped();
         }
       }

概要: セッション (SimpleSession) が DefaultSessionManage で作成されると、DelegatingSession にカプセル化されます。元のデータは適切に保存されるため、クライアントは元のデータを自由に変更できません。

以上がhiroのソースコード学習におけるSession session = getSession()の解析例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:Ant を使い始める次の記事:Ant を使い始める