Apple WebObjects 3.5 User Manual

Page 116

Advertising
background image

Chapter 7

Managing State

116

// WebScript
elapsedTime = [[self session] timeSinceSessionBegan];

//Java
elapsedTime = this.session().timeSinceSessionBegan();

The application object can also access session state using the same method
defined in WOApplication.

The WOSession class provides a dictionary where state can be stored by
associating it with a key. WOSession’s

setObject:forKey:

and

objectForKey

methods (in

Java,

setObject

and

objectForKey

) give access to this dictionary. For an example of

when this session dictionary might be useful, consider a web site that collects
users’ preferences about movies. At this web site, users work their way through
page after page of movie listings, selecting their favorite movie on each page. At
the bottom of each page, a “Choices” component displays the favorites that
have been picked so far in the user’s session. The Choices component is a
general-purpose reusable component that might be found in various
applications.

The designer of the Choices component decided to store the sessionwide list in
the session dictionary:

[[self session] setObject:

usersChoiceArray

forKey:@"Choices"];

By storing the information in the session dictionary rather than in a discrete
session instance variable, this component can be added to any application
without requiring code changes such as adding variables to the session object.

This approach works well until you have multiple instances of a reusable
component in the same page. For example, what if users were asked to pick
their most and least favorite movies from each list, with the results being
displayed in two different Choices components in each page. In this case, each
component would have to store its data under a separate key, such as
“BestChoices” and “WorstChoices”.

A more general solution to the problem of storing state when there are multiple
instances of a reusable component is to store the state under unique keys in the
session dictionary. One way to create such keys is to concatenate the
component’s name, context ID, and element IDs:

Advertising