Close

Primefaces - Idle Monitor

[Updated: May 7, 2018, Created: May 6, 2018]

IdleMonitor is a way to get notifications when user goes idle or from idle to active.

Example

Following example shows how to use idle/active ajax behavior events and client side Javascript events when user goes idle or active.

JSF Page

src/main/webapp/index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
    <h2>PrimeFaces - IdleMonitor + Ajax Example</h2>
    <h:form>
        <p:idleMonitor timeout="3000"
                       onidle="console.log('idle: '+(new Date()))"
                       onactive="console.log('active: '+(new Date()))">
            <p:ajax event="idle" listener="#{userBean.onIdle}" update="logs"/>
            <p:ajax event="active" listener="#{userBean.onActive}" update="logs"/>
        </p:idleMonitor>
        <br/>
        <h:panelGroup id="logs">
            <ui:repeat value="#{userBean.logs}" var="log">
                <div> #{log}</div>
            </ui:repeat>
        </h:panelGroup>
    </h:form>
</h:body>
</html>

We purposely kept idle timeout very low (3 sec) for testing our example.

Managed Bean

@ManagedBean
@ViewScoped
public class UserBean {
  private List<String> logs = new ArrayList<>();

  public void onIdle(AjaxBehaviorEvent ae) {
      logs.add("idle: " + LocalDateTime.now());
  }

  public void onActive(AjaxBehaviorEvent ae) {
      logs.add("active: " + LocalDateTime.now());

  }

  public List<String> getLogs() {
      return logs;
  }
}

output

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run

On going idle multiple times and activate browser window again:

On Chrome developer console:

Example Project

Dependencies and Technologies Used:

  • primefaces 6.2: PrimeFaces is one of the most popular UI libraries in Java EE Ecosystem and widely used by software companies, world renowned brands, banks, financial institutions, insurance companies, universities and more. [Description from primefaces-6.2.pom]
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

IdleMonitor with Ajax Behavior Events. Select All Download
  • primefaces-idle-monitor-with-ajax-events
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also