Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

  • 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 is 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.

...

Code Block
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);
	}
}));

...

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 object person). The simplest PropertyModel constructor is:

...

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, method 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 conversionThe model associates a different property expression with the component being bound.

Code Block
public <S> ComponentIModel<S> 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.

property)

With this association in place the child component can have whatever name we like, rather than having the match the property expression.

To use CompoundPropertyModel.bind To use BoundCompoundPropertyModel for the city field discussed above we might do something like this:

Code Block
BoundCompoundPropertyModelCompoundPropertyModel personModel = new BoundCompoundPropertyModelCompoundPropertyModel(person);
Form personForm = new Form("aPersonForm", personModel);
TextField cityField = new RequiredTextField("city");
personForm.add(cityField);
, personModel.bind(cityField, "address.city"));
personForm.add(cityField);

Note that the bind methods return the child component, thus the above can be more compactly written:

Code Block

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 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:

...

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

Code Block

protected abstract java.lang.Object load();

For example:

Code Block

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:

Code Block

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:

Code Block

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.

At the end of each request cycle the active page is serialized into a byte array and stored for the next request (some in the session and some to disk: see IPageStore for more info). The entire object graph of the page including all components and their associated models are included in generated byte stream (byte array). Once you get past all but the most trivial of applications this object graph becomes huge and the time required to serialize it becomes a bottle neck. Keeping the size of the serialized pages low will increase the number of concurrent users your application can support. It will also minimize the amount of time required to fail over to another cluster node and the bandwidth to keep the sessions replicated.

The Wicket solution to this problem is to create the concept of detachability where by at the end of the request cycle all the components contained in a page are recursively detached (See Component.detatch()) which dramatically reduces the size of the object graph being serialized. Each component in turn then detaches its internal state including the value of its default model by calling the IModel.detach() method.

So a Detachable Model is an IModel that releases most of its object graph when you call detatch() retaining just enough detail (typically a unique identifier) that can be used to reconstitute the object on the next call to getObject() which will occur on the next page render.

Two commonly used built-in Wicket IModel implementations are:

  1. AbstractReadOnlyModel
  2. LoadableDetachableModel (also commonly referred to as an LDM)

It is also possible to create a custom IModel implementation that mirrors the LoadableDetchableModel inner workings but also supporting IModel.setObject().

Managing the lifecycle of non default detachable IModel's

Wicket provides the detachability hooks and will automatically detach the default model of each component. However its common to use more than a single IModel implementation per component especially when using nested or chaining models. In this case the developer is responsible for registering their custom models to participate in the detachment process.

The best way to handle this registration is to make sure it occurs in the same scope as where the IModel implementation was instantiated.

For example:

Code Block


public class MyPanel extends Panel {

   private final DetatchableModelA detachableModelA;


   public MyPanel (String id) {
       super(id);

       this.detachableModelA = new DetachableModelA();

       add (new CustomFormPanel ("formPanel", new CListModelFromA (this.detachableModelA)));

   }

   @Override
   public void detach() {

     // remember to call the parent detach logic
     super.detach();

     this.detachableModelA.detach();

   }
}

Here you see that the DetachableModelA instance is created in the MyPanel constructor and then passed in as the inner model to the CListModelFromA model which will load a List<C> instances based on the details of the A instance contained in the model. Because the this.detachableModelA instance could possibly be shared like this in many sub component models its important that the CListModelFromA implementation does not try and call detach() on it but rather leave the detachment to occur in the same scope that the model was instantiated. In this case the detachment is done in the MyPanel.detach.

AbstractReadOnlyModel

When you subclass AbstractReadOnlyModel you implement the:

Code Block

public abstract T getObject();

So long as your subclass does not contain any private fields then no business data will be serialized when the the request cycle ends. The model object value is computed
at the time the method is called and not cached anywhere.

For example:

Code Block

public class PersonNameModel extends AbstractReadOnlyModel<String> {

    private final IModel<Person>personModel;

    public PersonNameModel (IModel<Person>personContainingModel> personModel) {
        this.personModel = personModel;
    }

    public String getObject() {
        Person p = this.personModel.getObject();

        if (p == null)
            return "";

        return p.getName();
    }

}

You can see it takes in an existing IModel that contains the Person object and that the getObject() method extracts the name of the person.

LoadableDetachableModel

This class extends AbstractReadOnlyModel and finalizes the IModel.getObject() method requiring you to implement:

Code Block

protected abstract T load();

This method is called once per request cycle, the first time that the getObject() method is invoked. The T object value is then cached in a transient private field and used as the return value to all subsequent calls to getObject().

For example:

Code Block

class LoadablePersonModel extends LoadableDetachableModel<Person> {

	Long id;

	LoadablePersonModel(Long id)	 {
		this.id = id;
	}

	@Override
	protected Person 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.

Read/Write Detachable Model

Here is an example of how to create a model that is loadable and detachable but also supports using the IModel.setObject(T value) to store a different value into the model.

Code Block

public class LoadableDetachableAttributeModel implements
		IModel<Attribute> {


	private transient Attribute cachedAttribute = null;
        private transient boolean attached = false;
	
	private String attributeName = null;

        private final AttributeService service;

	public LoadableDetachableAttributeModel (AttributeService service) {
            this.service = service;
        }
    

	public LoadableDetachableAttributeModel (AttributeService service, Attribute defaultValue) {
	      this (service);
              if (defaultValue != null) {
                   setObject(defaultValue);
              }
	}
	
	/* (non-Javadoc)
	 * @see org.apache.wicket.model.IDetachable#detach()
	 */
	@Override
	public void detach() {

                attached = false;
		cachedAttribute = null;
	}

	/* (non-Javadoc)
	 * @see org.apache.wicket.model.IModel#getObject()
	 */
	@Override
	public Attribute getObject() {

                if (!attached) {
                
                    // load the attribute
                    attached = true;
                    
                    if (attributeName != null) {

                       // load the attribute from the service
                       this.cachedAttribute = service.loadAttribute (this.attributeName);
                    }
                }
                return this.cachedAttribute;

	}

	/* (non-Javadoc)
	 * @see org.apache.wicket.model.IModel#setObject(java.lang.Object)
	 */
	@Override
	public void setObject(Attribute object) {

                this.attached = true;

		if (object == null) {
		      this.attributeName = null;
                      this.cachedAttribute = null;			
		}
		else {
			attributeName = object.getName();
                        this.cachedAttribute = object;
		}		
		
	}
	
	

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:

Code Block

CompoundPropertyModel personModel = new CompoundPropertyModel(new LoadablePersonModel(personId));

(here LoadablePersonModel is a subclass of CompoundPropertyModel, 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:

Code Block

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.

Panel

The IModel interface was simplified in Wicket 2.0:

Code Block

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.

Refactor Safe Property Models

Annotation processors

There are a number of annotation processors that generate a meta data that can be used to build safe property models. Examples of such processors:

LambdaJ

With a little bit of help from the LambdaJ project we can stop using fragile PropertyModels.

Code Block

/* www.starjar.com
 * Copyright (c) 2011 Peter Henderson. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0
 */
package com.starjar.wicket;

import ch.lambdaj.function.argument.Argument;
import ch.lambdaj.function.argument.ArgumentsFactory;
import org.apache.wicket.model.PropertyModel;

public class ModelFactory {

  /**
   * Use with the on() function from Lambdaj to have refactor safe property models.
   *
   * e.g.
   * <pre>
   * import static com.starjar.wicket.ModelFactory.*;
   * import static ch.lambdaj.Lambda.*;
   *
   * Contact contact = getContactFromDB();
   *
   * Label l = new Label("id", model(contact, on(Contact.class).getFirstName()));
   *
   *
   * </pre>
   *
   * OR
   *
   * <pre>
   * import static com.starjar.wicket.ModelFactory.*;
   * import static ch.lambdaj.Lambda.*;
   *
   * ContactLDM contactLDM = new ContactLDM(contactId);
   *
   * Label l = new Label("id", model(contactLDM, on(Contact.class).getFirstName()));
   * </pre>
   *
   * Works as expected for nested objects
   *
   * <pre>
   * Label l = new Label("address", model(contactLDM, on(Contact.class).getAddress().getLine1()));
   * </pre>
   *
   *
   * @param <T> Type of the model value
   * @param value
   * @param proxiedValue
   * @return
   */
  public static <T> PropertyModel<T> model(Object value, T proxiedValue) {
    Argument<T> a = ArgumentsFactory.actualArgument(proxiedValue);
    String invokedPN = a.getInkvokedPropertyName();
    PropertyModel<T> m = new PropertyModel<T>(value, invokedPN);
    return m;
  }
}

Which can then be used

Code Block

import static ch.lambdaj.Lambda.*;
import static com.starjar.wicket.ModelFactory.*;


public class MyPanel extends Panel {
  public MyPanel(String id) {
    Label l = new Label("firstName", model(contact, on(Contact.class).getFirstName());
    add(l);
    Label addr = new Label("address", model(contact, on(Contact.class).getAddress().getLine1());
    add(addr);
  }
}
Panel

The IModel interface was simplified in Wicket 2.0:

Code Block

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.