Warning | |
---|---|
There is very little reason to implement persistent page properties manually. Using
the |
The preferred way to
implement persistent page properties without using
the <property-specification>
element is to implement the method initialize()
on your page. This method is invoked
once when the page is first created; it is invoked again at the end of each request cycle. An empty implementation
of this method is provided by AbstractPage
.
The first example demonstrates how to properly implement a transient property. It is simply
a normal JavaBean property implementation, with a little extra to reset the property
back to its pristine value (null
) at the end of the request.
Example 4.5. Use of initialize()
method
package mypackage;
import org.apache.tapestry.html.BasePage;
public class MyPage extends BasePage
{
private String _message;
public String getMessage()
{
return _message;
}
public void setMessage(String message)
{
_message = message;
}
protected void initialize()
{
_message = null;
}
}
If your page has additional attributes, they should also be reset inside
the initialize()
method.
Now that we've shown how to manually implement transient state, we'll show how to handle persistent state.
For a property to be persistent, all that's necessary is that the accessor method notify
the framework of changes. Tapestry will record the changes (using an IPageRecorder
)
and, in later request cycles, will restore the property
using using the recorded value and whichever page instance is taken out of the page pool.
This notification takes the form of an invocation of the static method
fireObservedChange()
in the Tapestry
class.
This method is overloaded for all the scalar types, and for Object
.
Example 4.6. Manual persistent page property
package mypackage;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.html.BasePage;
public class MyPage extends BasePage
{
private int _itemsPerPage;
public int getItemsPerPage()
{
return _itemsPerPage;
}
public void setItemsPerPage(int itemsPerPage)
{
_itemsPerPage = itemsPerPage;
Tapestry.fireObservedChange(this, "itemsPerPage", itemsPerPage);
}
protected void initialize()
{
_itemsPerPage = 10;
}
}
This sets up a property, itemsPerPage
, with a default value of 10. If
the value is changed (perhaps by a form or a listener method),
the changed value will "stick" with the user who changed it, for the duration of their
session.