NOTE: this page is about models like they exist for Wicket 1.x. The IModel interface is slightly changed in Wicket 2.x. Most of what is written on this page applies to Wicket 2.x as well, but where it doesn't there will be notes.
What are Wicket Models?
In Wicket, a model holds a value for a component to display and/or edit. How exactly this value is held is determined by a given model's implementation of the wicket.model.IModel
interface. The IModel interface decouples a component from the model object which forms its value. This in turn decouples the whole Wicket framework from any and all details of model storage, such as the details of a given persistence technology. As far as Wicket itself is concerned, a model is anything that implements the IModel interface, no matter how it might do that. Although there are some refinements described below, conceptually, IModel looks like this:
public interface IModel { public Object getObject(); public void setObject(final Object object); }
The IModel interface defines a simple contract for getting and setting a value. The nature of the Object retrieved or set will depend on the component referencing the model. For a Label
component, the value must be something which can be converted to a String
which will be displayed when the label is rendered. For a ListView
, it must be a java.util.List
containing the values to be displayed as a list.
Different frameworks implement the model concept differently. Swing has a number of component-specific model interfaces. Struts requires that the model be a Java Bean and there is no explicit model interface. The IModel interface in Wicket allows models to be generic (as in Struts) but it can do things that would not be possible if components accessed their model directly (as in Swing). For example, Wicket applications can use or provide IModel implementations that read a model value from a resource file or retrieve a model value from a database only when needed.
The use of a single model interface (as compared to having multiple interfaces, or having no model interface at all) has a number of advantages:
- Wicket provides
IModel
implementations you can use with any component. These models can do things such as retrieve the value from a resource file, or read and write the value from a Java Bean property. - Wicket also provides
IModel
implementations that defer retrieving the value until it is actually needed, and remove it from the servlet Session when the request is complete. This reduces session memory consumption, and it particularly useful with large values such as lists. - Unlike Swing, you do not have to implement an extra interface or helper class for each different component. Especially for the most often used components such as Labels and TextFields you can easily bind to a bean property.
- In many cases you can provide the required value directly to the component and it will wrap a default model implementation around it for you.
- And while you do not have to use beans as your models as you must with Struts, you may still easily use beans if you wish. Wicket provides the appropriate model implementations.
Simple Models
The HelloWorld example program demonstrates the simplest model type in Wicket:
public class HelloWorld extends WicketExamplePage { public HelloWorld() { add(new Label("message", "Hello World!")); } }
The constructor for this page constructs a Label component. The first parameter to the Label component's constructor is the Wicket id, which associates the Label with a tag in the HelloWorld.html markup file:
<?xml version="1.0" encoding="UTF-8"?> <html xmlns:wicket='http://wicket.sourceforge.net/wicket'> <head> <title>Wicket Examples - helloworld</title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <span wicket:id="mainNavigation"/> <span wicket:id="message">Message goes here</span> </body> </html>
The second parameter to the Label component's constructor is the model data for the Label, providing content that replaces any text inside the <span>
tag to which the Label is associated. The model data passed to the Label constructor above is apparently a String. Internally Label creates a Model
for the String. Model
is a simple default implementation of IModel
.
Thus instead we could have created our label this way:
add(new Label("message", new Model("Hello World!")));
The Label constructor that takes a String is simply a convenience.
Dynamic Models
The data we gave to the model in the previous example, the string "Hello World", is constant. No matter how many times Wicket asks for the model data, it will get the same thing. Now consider a slightly more complex example:
Label name = new Label ("name", new Model(person.getName()));
The model data is still a String, the value of person.getName()
is set at the time the model is created. Recall that Java strings are immutable: this string will never change. Even if person.getName() would later return a different value, the model data is unchanged. So the page will still display the old value to the user even if it is reloaded. Models like this, whose values never change, are known as static models.
In many cases the underlying data can change, and you want the user to see those changes. For example, the user might use a form to change a person's name. Models which can automatically reflect change are known as dynamic models. While the Model
class is static, most of the other core Wicket model classes are dynamic.
It's instructive to see how to make a dynamic model by subclassing Model
.
personForm.add(new RequiredTextField("personName", new Model() { @Override public Object getObject(Component component) { return person.getName(); } @Override public void setObject(Serializable object) { person.setName((String) object); } }));
It would be inconvenient to have to do this for every component that needs a dynamic model. Instead, you can use the PropertyModel
class or one of the other classes described below.
Property Models
The PropertyModel class allows you to create a model that accesses a particular property of its associated model object at runtime. This property is accessed using a simple expression language with a dot notation (e.g. 'name'
means property 'name'
, and 'person.name'
means property name
of property person
). The simplest PropertyModel constructor is:
public PropertyModel(final Object modelObject, final String expression)
which takes a model object and a property expression. When the property model is asked for its value by the framework, it will use the property expression to access the model object's property. For example, if we have a Java Bean or "POJO" (Plain Old Java Object) like this:
class Person { private String name; Person(String name) { this.name = name; } String getName() { return name; } }
then the property expression "name
" can be used to access the "name
" property of any Person object via the getName()
getter method.
personForm.add(new RequiredTextField("personName", new PropertyModel(person, "name")));
Nested property expressions are possible as well. You can access sub-properties via reflection using a dotted path notation, which means the property expression "person.name"
is equivalent to calling getPerson().getName()
on the given model object.
A second constructor on PropertyModel is available for models that wish to access properties involving type conversions:
public PropertyModel(final Object modelObject, final String expression, Class propertyType)
Although the property models will do automatic type conversions for you, it may not always do the kind of conversion you desire. This alternative constructor creates a property model that forces a particular conversion to occur. For example, you may wish to access a String or Object property of something as an Integer. Constructing a PropertyModel with new PropertyModel(object, "myString", Integer.class)
would force the property to be converted to and from an Integer on get/set operations.
There are three principal reasons why you might use PropertyModel instead of Model:
- PropertyModel instances are dynamic
- the property expression language is more compact than the analogous Java code
- it's much simpler to create a property model than to subclass
Model
Compound Property Models
Compound models allow containers to share models with their children. This saves memory, but more importantly, it makes replication of models much cheaper in a clustered environment. The basic idea is that the contained components usually want model data that can be easily derived at runtime from the model of their container. So, give the contained components no explicit model, and when a model is needed, Wicket will search up the containment hierarchy for a compound model. The compound model can retrieve model data for any of its contained components.
CompoundPropertyModel is the most commonly used compound model. An instance of this class uses the name of the contained component as a property expression to retrieve data from its own model data.
To use a CompoundPropertyModel
, simply set one as the model for a container, such as a Form or a Page. Create the contained components with no model of their own. Insure that the component identifier names match the appropriate property names.
Here's a simple example using a CompoundPropertyModel. Suppose we have a Person class, with two properties: Name and Age. We want a simple form for the user to edit a Person.
Form personForm = new Form("aPersonForm", new CompoundPropertyModel(person)); personForm.add(new RequiredTextField("name")); personForm.add(new RequiredTextField("age", Integer.class));
(A complete working example would require a save button and so forth but the use of a compound model doesn't change those.)
The component name can in fact be a more complicated property expression. Suppose for example that the Person class also has an address property, of class Address
, and that class in turn has a city property. To define this field in the form we can do this:
personForm.add(new RequiredTextField("address.city"));
The corresponding input field in the html must have a wicket id of "address.city". This works, but it does expose the internal structure of the model data in the html. CompoundPropertyModel
has a subclass, BoundCompoundPropertyModel
, that can be used to rectify this.
BoundCompoundPropertyModel
adds three new methods. They associate a child component of the model with a specific property expression and/or type conversion.
public Component bind(final Component component, final String propertyExpression) public Component bind(final Component component, final Class type) public Component bind(final Component component, final String propertyExpression, final Class type)
With this association in place the child component can have whatever name we like, rather than having the match the property expression.
To use BoundCompoundPropertyModel
for the city field discussed above we might do something like this:
BoundCompoundPropertyModel personModel = new BoundCompoundPropertyModel(person); Form personForm = new Form("aPersonForm", personModel); TextField cityField = new RequiredTextField("city"); personForm.add(cityField); personModel.bind(cityField, "address.city");
Note that the bind methods return the child component, thus the above can be more compactly written:
BoundCompoundPropertyModel personModel = new BoundCompoundPropertyModel(person); Form personForm = new Form("aPersonForm", personModel); personForm.add(personModel.bind(new RequiredTextField("city"), "address.city"));
Also, note that if you are using a component that you do not want to reference the compound property model, but is a child of the form, that you define a model for that component. For example:
// throws exception personForm.add(new Label("non-compound-model-reference")); // does not throw an exception personForm.add(new Label("non-compound-model-reference", new Model()));
Wrapped Object Models
It is possible to create Models that explicitly define in normal java code what is to be returned as the model object for each property within the object being wrapped. So instead of specifying via a string the name of the property to fetch the value you from the specification is done in Java.
While creating Model's in this pattern takes longer (more classes) than using Reflection based PropertyModels it prevents the problems that can occur when critical functionality is defined in String based context that most IDE's do not refactor properly.
It also helps with readability when the models are added to components to be able to easily see the types involved.
These are the Address and Person classes used in the previous examples:
public class Address implements Serializable { private String city; public Address() { super(); } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } public class Person implements Serializable { private String name; private int age; private Address address; public Person() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
The first step is to create a Wrapped Object Model for the Address and Person classes:
public class AddressModel implements IModel { private IModel addressContainingModel; private AddressModelType type; public enum AddressModelType { CITY_MODEL; }; public AddressModel(IModel addressContainingModel, AddressModelType type) { this.addressContainingModel = addressContainingModel; this.type = type; } @Override public Object getObject() { Address address = (Address) addressContainingModel.getObject(); switch (type) { case CITY_MODEL: return address.getCity(); } throw new UnsupportedOperationException("invalid AddressModelType = " + type.name()); } @Override public void setObject(Object object) { Address address = (Address) addressContainingModel.getObject(); switch (type) { case CITY_MODEL: address.setCity((String) object); break; default: throw new UnsupportedOperationException("invalid AddressModelType = " + type.name()); } } @Override public void detach() { addressContainingModel.detach(); } } public class PersonModel implements IModel { private IModel personContainingModel; private PersonModelType type; public enum PersonModelType { NAME_MODEL, AGE_MODEL, ADDRESS_MODEL; } public PersonModel(IModel personContainingModel, PersonModelType type) { this.personContainingModel = personContainingModel; this.type = type; } @Override public Object getObject() { Person person = (Person) personContainingModel.getObject(); switch (type) { case NAME_MODEL: return person.getName(); case AGE_MODEL: return new Integer(person.getAge()); case ADDRESS_MODEL: return person.getAddress(); } throw new UnsupportedOperationException("invalid PersonModelType = " + type.name()); } @Override public void setObject(Object object) { Person person = (Person) personContainingModel.getObject(); switch (type) { case NAME_MODEL: person.setName((String) object); break; case AGE_MODEL: person.setAge((Integer) object); break; case ADDRESS_MODEL: person.setAddress((Address) object); break; default: throw new UnsupportedOperationException("invalid PersonModelType = " + type.name()); } } @Override public void detach() { personContainingModel.detach(); } }
Notice how each wrapped model contains an inner model that contains the actual pojo instance. This allows for the wrapped model to be a plain Model or a LoadableDetachableModel, or even another wrapped model where its .getObject() results in a suitably typed input value (see the "address.city" field in the example below).
At this point to create a form using our wrapped object models looks like:
Person p = new Person (); Form personForm = new Form("aPersonForm"); personForm.add(new RequiredTextField("name", new PersonModel (new Model (p), PersonModelType.NAME_MODEL))); personForm.add(new RequiredTextField("age", new PersonModel (new Model (p), PersonModelType.AGE_MODEL), Integer.class)); personForm.add(new RequiredTextField("address.city", new AddressModel (new PersonModel (new Model (p), PersonModelType.ADDRESS_MODEL), AddressModelType.CITY_MODEL))); add(personForm);
A wrapped object model also makes working with DataTables's easier as one IColumn implementation can be written for each object class which makes the declaration of the table much simpler.
e.g.
public class PersonTableColumn extends AbstractColumn { private final PersonModelType type; public PersonTableColumn(String columnName, PersonModelType type) { super(new Model(columnName)); this.type = type; } public void populateItem(Item cellItem, String componentId, IModel rowModel) { switch (type) { // this needs to be handled seperately due to it being an Address // instance from the Person object. case ADDRESS_MODEL: cellItem .add(new Label(componentId, new AddressModel(new PersonModel(rowModel, PersonModelType.ADDRESS_MODEL), AddressModelType.CITY_MODEL))); break; default: cellItem.add(new Label(componentId, new PersonModel(rowModel, type))); } } }
So the table could be declared like:
DataTable table = new DataTable("datatable", new IColumn[] { new PersonTableColumn("Name", PersonModelType.NAME_MODEL), new PersonTableColumn("Age", PersonModelType.AGE_MODEL), new PersonTableColumn("City", PersonModelType.ADDRESS_MODEL) }, new PersonProvider(), 10);
Another option with the complex object is to create a custom IConverter that will take in this case the Address instance from the PersonModel and render the string value as the city name.
e.g.
public class CustomLabel extends Label { private final IConverter converter; /** * @param id * @param label */ public CustomLabel(String id, IModel labelModel, IConverter converter) { super(id, labelModel); this.converter = converter; } /* (non-Javadoc) * @see org.apache.wicket.Component#getConverter(java.lang.Class) */ @Override public IConverter getConverter(Class type) { return this.converter; } }
With the populate from above as:
public void populateItem(Item cellItem, String componentId, IModel rowModel) { switch (type) { case ADDRESS_MODEL: cellItem .add(new CustomLabel(componentId, new PersonModel(rowModel, PersonModelType.ADDRESS_MODEL), new IConverter() { public Object convertToObject(String arg0, Locale arg1) { throw new UnsupportedOperationException("converter is readonly."); } public String convertToString(Object object, Locale locale) { Address address = (Address) object; return address.getCity(); } })); break; default: cellItem.add(new Label(componentId, new PersonModel(rowModel, type))); } }
Resource Models
Localization of resources in Wicket is supported by the Localizer
class. This provides a very convenient way to retrieve and format application-wide or component-specific resources according to the Locale that the user's Session is running under. You can retrieve a String
using Localizer
and use the result as a model object, but it is usually more convenient to use one of Wicket's resource model classes.
ResourceModel
is the simplest of these. It simply takes a resource key and uses it to determine the model object (by looking for the resource in a property file). Thus for a example a label can be created this way:
add(new Label("greetings", new ResourceModel("label.greetings")));
(Note however that you can also accomplish the same thing using the wicket:message tag in the html.)
ResourceModel
has another constructor which takes an additional string to be used as a default if the resource is not found.
The model objects created via ResourceModel
vary according to the locale and the contents of the resource bundle, but they don't otherwise depend on the program state. For example, the greeting message produced above doesn't contain the user's name. More dynamic models can be constructed using StringResourceModel
.
StringResourceModels have a resource key, a Component, an optional model and an optional array of parameters that can be passed to the Java MessageFormat facility. The constructors look like this:
public StringResourceModel(final String resourceKey, final Component component, final IModel model) public StringResourceModel(final String resourceKey, final Component component, final IModel model, final Object[] parameters)
The resourceKey is used to find the resource in a property file. The property file used depends on the component.
A very simple example of a StringResourceModel
might be a Label constructed like this:
add(new Label("greetings", new StringResourceModel("label.greetings", this, null)));
where the resource bundle for the page contains an entry like this:
label.greetings=Welcome!
This label is essentially the same as that constructed with ResourceModel
above. However, with StringResourceModel
we can add the name from a User object to the greeting. We pass the user object as the model parameter to the constructor. Wicket will find the localized string in the resource bundle, find any substrings within it of the form ${propertyexpression}, and replace these substrings with their values as property expressions. The model is used to evaluate the property expressions.
For example, suppose we wanted to add the name from a User object to the greeting above. We'd say:
User user; ... add(new Label("greetings", new StringResourceModel("label.greetings", this, new Model(user))));
and have a resource like:
label.greetings=Welcome, ${name}!
where User has a getName()
method exposing its "name"
property.
Note that StringResourceModel
is dynamic: the property expression is re-evaluated every time getObject()
is called. In contrast, if the application code called Localizer
itself and used the resulting string as model data, the result would be a static (non-changing) model.
Detachable Models
Wicket maintains information about recently created pages in the servlet Session. The models for the pages' components are a large portion of this data. There are several motivations for reducing the amount of memory consumed by this data. It increases the number of users that can be served with the same amount of memory. Also, we may wish to replicate session data in a cluster so we can move sessions if a web server fails, and in this case there is serialization overhead we want to minimize.
It's quite common that model data contains some very small sub-part, such as a database identifier, from which the rest of the object can be reconstituted. So one way to reduce Session memory usage is to discard the data when display of the page is complete, except for the small special piece needed to recover the rest. Wicket supports this via detachable models.
The easiest way to create a detachable model is to extend LoadableDetachableModel
. This class has an abstract method
protected abstract java.lang.Object load();
For example:
class LoadablePersonModel extends LoadableDetachableModel { Long id; LoadablePersonModel(Long id) { this.id = id; } @Override protected Object load() { return DataManager.getPersonFromDatabase(id); } }
When getObject()
is called for the first time on a given instance of this class, it will call load()
to retrieve the data. At this point the data is said to be attached. Subsequent calls to getObject()
will return the attached data. At some point (after the page has been rendered) this data will be removed (the internal references to it will be set to null). The data is now detached. If getObject()
is subsequently called (for example, if the page is rendered again), the data will be attached again, and the cycle starts anew.
Chaining models
Suppose you want a model that is both a loadable model and a compound model, or some other combination of the model types described above. One way to achieve this is to chain models, like this:
CompoundPropertyModel personModel = new CompoundPropertyModel(new LoadablePersonModel(personId));
(here LoadablePersonModel
is a subclass of LoadableDetachableModel
, as described earlier)
The model classes in the core Wicket distribution support chaining where it make sense.
More about the IModel interface
We are now in a position to understand the complete IModel
interface:
public interface IModel extends IDetachable { public Object getNestedModel(); public Object getObject(final Component component); public void setObject(final Component component, final Object object); }
IModel
extends IDetachable
, which means that all models must provide a method public void detach()
. Some model classes (Model
for one) provide an empty, no-op implementation.
In some cases model instances form a natural hierarchy. For example, several CompoundPropertyModels
share the same model object. The getNestedModel()
method will return this common shared object. In cases where there is no such object it returns null
.
Compound models are also the motivation for the component
parameters to getObject
and setObject
. Several components may share the same CompoundPropertyModel
object. If getObject
(or setObject
) is called it must return something different depending on the component (e.g., evaluate the appropriate property expression). Thus these two methods must be passed a component as a parameter.
The IModel interface was simplified in Wicket 2.0:
public interface IModel<T> extends IDetachable { T getObject(); void setObject(final T object); }
The get and set methods do not take a component argument anymore. Instead, Wicket 2.0 has specialized model interfaces to do with specific issues like recording the 'owning' component of a model. See IAssignmentAwareModel and IInheritableModel (though you typically don't need to know these interfaces directly).
Another change is that IModel does now support generics. This is especially interesting when authoring custom components where you allow only models (compile time) that produce a certain type. ListView for instance only accepts models that produces instances of java.util.List.