一種方法是定期檢查服務器是否發生超時。您將不得不編寫一個servlet方法來執行該檢查,而不會更新服務器會話超時!當然這會導致很多服務器命中。 (不一定是壞的方法雖然!)
但是,也許我會用一個dfifferent解決方案,它試圖保持一個計時器在客戶端與服務器的定時器,例如大約同步
客戶端:
import com.google.gwt.user.client.Timer;
public class ClientTimers {
private static final Timer SESSION_MAY_HAVE_EXPIRED_TIMER = new Timer() {
@Override
public void run() {
// Warn the user, that the session may have expired.
// You could then show a login dialog, etc...
}
};
public static void renewSessionTimer() {
// First cancel the previous timer
SESSION_MAY_HAVE_EXPIRED_TIMER.cancel();
// Schedule again in 5 minutes (maybe make that configurable?)
// Actually, let's subtract 10 seconds from that, because our timer
// won't be synchronized perfectly with the server's timer.
SESSION_MAY_HAVE_EXPIRED_TIMER.schedule(5 * 60 * 1000 - 10000);
}
}
我假設你的服務器會話超時被更新的每一個客戶端執行與服務器,例如交互時間一個GWT-RPC調用(如果該會話還沒有超時)。
所以在客戶端,然後,我會還更新客戶端計時器,以保持它的大致同步:
myService.performSomeAction(...) {
@Override
public void onSuccess(String result) {
ClientTimers.renewSessionTimer();
// remaining onSuccess handling
}
@Override
public void onFailure(Throwable caught) {
if (failedBecauseOfSessionTimeout()) {
// redirect to login
} else {
ClientTimers.renewSessionTimer();
// remaining onFailure handling...
}
}
}
不要忘記尤其是直接調用後renewSessionTimer()上的所有交互(登錄)。
重要說明:對於所有安全檢查,僅使用服務器會話。客戶端「會話計時器」僅爲用戶提供便利。不要根據該定時器或任何類型的客戶端會話進行安全/授權檢查。