在我的Web应用程序中,我有一个空闲监视器,如果用户空闲5分钟,则会触发。它将打开一个确认对话框,该对话将等待2分钟;之后,它将重定向到登录页面。
要求:我想显示一个倒数计时器,剩余时间将用户重定向到登录页面。
basetemplate.xhtml:
<h:form>
<p:idleMonitor timeout="#{idleMonitorView.timeoutVal}"
onidle="startTimer()" />
<p:confirmDialog id="confirmDialog"
message="You have been idle, Please click ok to remain logged in"
header="Are you there?" severity="alert" widgetVar="idleDialog">
<p:commandButton id="confirm" value="Ok" oncomplete="extendSession()" />
</p:confirmDialog>
<p:remoteCommand name="terminateIdleSession" actionListener="#{idleMonitorView.onIdle}" out="count" />
<script type="text/javascript">
var extend_session = 0;
function startTimer() {
extend_session = 0;
setTimeout("timeout()", 120000);
PF('idleDialog').show();
}
function timeout() {
if (extend_session == 0) {
terminateIdleSession();
}
}
function extendSession() {
extend_session = 1;
PF('idleDialog').hide();
}
</script>
</h:form>
问题:我不知道如何达到这一要求。
您应该创建一个JavaScript间隔,该间隔每秒更新计时器(或您需要的任何其他间隔(。您可以使用一些jQuery更新计时器。我建议将跨度添加到对话框消息中,您可以用作计时器:
$("#myForm\:confirmDialog .ui-confirm-dialog-message").append("<span id=logoffTimeout/>");
您应该在此处使用您在表单上使用的ID替换myForm
。
显示对话框时,计算登录计时器将到期的时间并将其存储在window.logoffTime
中。现在,您可以使用以下功能更新计时器:
function updateTimer(){
var seconds = Math.ceil((window.logoffTime - new Date().getTime()) / 1000);
$("#logoffTimeout").html(seconds);
}
在您的按钮和远程命令上,我建议使用process="@this"
。另请参阅:了解PrimeFaces过程/更新和JSF F:AJAX执行/渲染属性
在JavaScript中启动超时时,您应该知道的是返回ID。您可以使用该ID清除超时。
我最终得到了这个xhtml:
<p:confirmDialog id="confirmDialog"
message="Please click Ok before the timer runs out: "
header="Are you there?"
severity="alert"
closable="false"
widgetVar="idleDialog">
<p:commandButton id="confirm"
value="Ok"
process="@this"
onclick="clearTimeout(window.logoffTimeoutId); PF('idleDialog').hide();"/>
</p:confirmDialog>
<p:remoteCommand name="terminateIdleSession"
actionListener="#{idleMonitorView.onIdle}"
process="@this"
out="count"/>
<p:idleMonitor timeout="#{5 * 60 * 1000}"
onidle="startTimer()"/>
和此JavaScript:
function startTimer() {
clearTimeout(window.logoffUpdaterId);
PF('idleDialog').show();
// Set timeout to 2 minutes
var timeout = 2 * 60 * 1000;
// Calculate when the time runs out
window.logoffTime = new Date().getTime() + timeout;
// Start timer which calls remote command
window.logoffTimeoutId = setTimeout(terminateIdleSession, timeout);
// Update timer every second
window.logoffUpdaterId = setInterval(updateTimer, 1000);
// Update timer now
updateTimer();
}
// Update the timer
function updateTimer() {
var seconds = Math.ceil((window.logoffTime - new Date().getTime()) / 1000);
$("#logoffTimeout").html(seconds);
}
// Create span to contain the timer
$(function(){
$("#myForm\:confirmDialog .ui-confirm-dialog-message").append("<span id=logoffTimeout/>");
});
我注意到您正在使用嵌入在XHTML中的JavaScript。在这种情况下,添加CDATA
以防止陷入XML错误:
<script type="text/javascript">
//<![CDATA[
...
//]]>
</script>
我建议从文件/资源中加载您的脚本,这将为您带来缓存的好处。