How can I store state for an individual browser tab/window?

Autogenerate an unique value on the initial GET request which you store and pass around on every subsequent postback as a hidden input value. Use this unique value as identifier of the session attribute representing the view-scoped data.

During the 1st request on a brand new session, do:

Map<String, ViewData> viewScope = new HashMap<String, ViewData>();
session.setAttribute("viewScope", viewScope);

(the ViewData represents the view-specific data you’d like to track across postbacks on the same view)

During every GET request, do:

String viewDataId = UUID.randomUUID().toString();
viewScope.put(viewDataId, new ViewData());
request.setAttribute("viewDataId", viewDataId);

During generating the HTML, do:

<input type="hidden" name="viewDataId" value="${viewDataId}" />

During every POST request, do:

ViewData viewData = viewScope.get(request.getParameter("viewDataId"));
// Get/set view-specific data in there.

Make sure that jQuery also passes this hidden input around (which shouldn’t be a big problem if you already properly use $(form).serialize() or e.g. AjaxForm plugin to ajaxify the forms).

If you’re familiar with Java EE’s MVC framework JSF, then it may be useful to know that its @ViewScoped annotation works roughly the same as described above. See also a.o. How to choose the right bean scope?

Leave a Comment