Datasheet

The following code is an example of retrieving and setting preferences:
try {
PortletPreferences myPrefs = request.getPreferences();
String [] cities =
myPrefs.getValues(“cities”,
new String[] {“20112”,”90210”});
for (int i=0; i < cities.length; i++) {
System.out.println(cities[i]);
}
String [] newCities = new String[] {“20169”,”22124”};
myPrefs.setValues(“cities”,newCities);
myPrefs.store();
} catch (ValidatorException ve) {
System.out.println(“Preferences did not validate.”);
} catch (UnmodifiableException ume) {
System.out.println(“The preference is not modifiable”);
} catch (IllegalStateException ise) {
System.out.println(“You cannot be in render!”);
}
Developers can define custom classes to provide validation of preferences. These classes implement the
PreferencesValidator interface and must provide their validation capability in a thread-safe manner.
Implementing a
PreferencesValidator is very simple: There is only one method, validate, which
takes a
PortletPreferences object and returns nothing. Simply throw a ValidatorException if any
of the values doesn’t meet the logic you define.
Sessions
Because portals are built upon the request-response paradigm (and predominantly upon HTTP), there
has to be some mechanism available to maintain state across invocations. For example, it isn’t sensible to
authenticate users with every request. There are several techniques to manage sessions, with cookies and
URL rewriting being two of the most popular in Web applications (cookies are used under the hood by
many servlet containers to implement the
HTTPSession).
Sessions are critical to portlet development, but there are many ways to implement them, so the Portlet
API provides the
PortletSession interface. When a client makes a request, the server sends a session
identifier in the response. If the client wants to join the session, the client provides that session identifier
with their next request.
The
PortletSession can be used to hold attributes. PortletSession operates much like HTTPSession
in this regard, providing the capability to store key-value pairs, with arbitrary objects. There is one major
difference. The
PortletSession has two different scopes:
APPLICATION_SCOPE is very similar to the HTTPSession scope. An object placed in this scope
is available to all the portlets within the session.
PORTLET_SCOPE refers to when an object is available to only that portlet.
PORTLET_SCOPE is unique in that it provides a namespace for the given attribute. For example, an attribute
called
city.name would be stored in javax.portlet.p.47?city.name. (“47” is an internally assigned
18
Chapter 1
04 469513 Ch01.qxd 1/16/04 11:04 AM Page 18