Tracking Events with Google Analytics in Struts Actions

Google Analytics

Google Analytics is a great marketing tool that can be used in order to get detailed information about the users of your web sites and their navigation patterns. The standard approach is to track page visits (where statistics can be aggregated by visited URLs), but there are times where you would want a higher granularity of which actions your users do, where these can’t be tracked exclusively by URL.

Analytics provides a mechanism called event tracking for that purpose. Events can be tracked by calling a JavaScript function _trackEvent. A sample usage would be:

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

// get a tracker with your user account code
var pageTracker = _gat._getTracker("UA-XXXXXX-X"); 

// optionally track the page view:
pageTracker._trackPageview();

// track an event:
pageTracker._trackEvent(category, event, label);

The parameters to track event (category, event and label) can be used within Analytics to obtain three levels of statistical aggregation of data. E.g. in our case we may use categories for login, document, subscription… Within document we have events for upload, sign, reject, add comment… As a label to document operations we may assign a user id, a document type, or however we wish the document events to be labelled for later analysis.

Integrating event tracking with Struts actions

Event tracking is based on a Javascript API, which means that you need to generate specific Javascript code within your pages depending on the results of your actions. This code must be present in the pages rendered as a consequence of the action, which sometimes may result in a redirect or action forward (for example, to a document list). A specific action may generate more than one event (e.g. “document was signed”, “user entered comments”).

The approach we used in order to be able to track events from within Struts can be summarised in the following steps:

  • An object associated with the user session keeps a list of generated events
  • A custom tag present in all pages flushes all pending events in the page (generates the Javascript code and clears the event list)
  • We include this custom tag as part of the default site template, so that it appears in all pages

Continue reading

Advertisements