7. Components lifecycle

Just like applets and servlets, also Wicket components follow a lifecycle during their existence. In this chapter we will analyze each stage of this cycle and we will learn how to make the most of the hook methods that are triggered when a component moves from one stage to another.

7.1. Lifecycle stages of a component

During its life a Wicket component goes through the following stages:

  1. Initialization: a component is instantiated and initialized by Wicket.

  2. Rendering: components are prepared for rendering and generate markup. If a component contains children (i.e. is a subclass of MarkupContainer) their rendering result is included in the resulting markup.

  3. Removed: this stage is triggered when a component is explicitly removed from its component hierarchy, i.e. when its parent invokes remove(component) on it. This stage is facultative and is never triggered for pages.

  4. Detached: after request processing has ended all components are notified to detach any state that is no longer needed.

The following picture shows the state diagram of component lifecycle:

component lifecycle

Once a component has been removed it could be added again to a container, but the initialization stage won’t be executed again - it is easier to just create a new component instance instead.

If you read the JavaDoc of class Component you will find a more detailed description of component lifecycle. However this description introduces some advanced topics we didn’t covered yet hence, to avoid confusion, in this chapter some details have been omitted and they will be covered later in the next chapters.

For now you can consider just the simplified version of the lifecycle described above.

7.2. Hook methods for component lifecycle

Class Component comes with a number of hook methods that can be overridden in order to customize component behavior during its lifecycle. In the following table these methods are grouped according to the stage in which they are invoked (and they are sorted by execution order):

Cycle stage

Involved methods

Initialization

constructor, onInitialize()

Rendering

onConfigure(), onBeforeRender(), renderHead(), onRender(), onComponentTag(), onComponentTagBody(), onAfterRender()

Removed

onRemove()

Detached

onDetach()

Now let’s take a closer look at each stage and its hook methods.

7.3. Initialization stage

This stage is the beginning of the component lifecycle.

A component is instantiated by application code (or by Wicket in case of bookmarkable page) and added to a parental component. As soon as the component is contained in a component tree rooted in a page, a “post”-constructor onInitialize() is called where we can execute custom initialization of our component.

When we override this method we have to call super.onInitialize(), usually before anything else in that method.

7.4. Rendering stage

This stage is reached each time a component is rendered, typically when a page is requested or when the component or one of its ancestors is refreshed via AJAX.

7.4.1. Method onConfigure

Method onConfigure() has been introduced in order to provide a good point to manage the component states such as its visibility or enabled state. This method is called on all components whose parent is visible.

As stated in chapter 6.1, isVisible() and isEnabled() are called multiple times when a page or a component is rendered, so it’s highly recommended not to directly override these method, but rather to use onConfigure() to change component states. On the contrary method onBeforeRender (see the next paragraph) is not indicated for this task because it will not be invoked if component visibility is set to false.

7.4.2. Method onBeforeRender

The most important hook method of this stage is probably onBeforeRender(). This method is called on all visible components before any of them are rendered. It is our last chance to change a component’s state prior to rendering - no change to a component’s state is allowed afterwards.

If we want to add/remove child components this is the right place to do it. In the next example (project LifeCycleStages) we will create a page which alternately displays two different labels, swapping between them each time it is rendered:

  1. public class HomePage extends WebPage
  2. {
  3. private Label firstLabel;
  4. private Label secondLabel;
  5. public HomePage(){
  6. firstLabel = new Label("label", "First label");
  7. secondLabel = new Label("label", "Second label");
  8. add(firstLabel);
  9. add(new Link<Void>("reload"){
  10. @Override
  11. public void onClick() {
  12. }
  13. });
  14. }
  15. @Override
  16. protected void onBeforeRender() {
  17. if(contains(firstLabel, true))
  18. replace(secondLabel);
  19. else
  20. replace(firstLabel);
  21. super.onBeforeRender();
  22. }
  23. }

The code inside onBeforeRender() is quite trivial as it just checks which label among firstLabel and secondLabel is currently inserted into the component hierarchy and it replaces the inserted label with the other one.

This method is also responsible for invoking children onBeforeRender(). So if we decide to override it, we have to call super.onBeforeRender(). However, unlike onInitialize(), the call to superclass method should be placed at the end of method’s body in order to affect children’s rendering with our custom code.

Please note that in the example above we can trigger the rendering stage pressing F5 key or clicking on link “reload”.

If we forget to call superclass version of methods onInitialize() or onBeforeRender(), Wicket will throw an IllegalStateException with the following message:
java.lang.IllegalStateException: org.apache.wicket.Component has not been properly initialized. Something in the hierarchy of <page class name> has not called super.onInitialize()/onBeforeRender() in the override of onInitialize()/ onBeforeRender() method

7.4.3. Method renderHead

This method gives all components the possibility to add items to the page header through its argument of type org.apache.wicket.markup.head.IHeaderResponse

7.4.4. Method onRender

This method does the actual rendering — you will rarely have to implement it, since most components already contain a specific implementation to produce their markup.

7.4.5. Method onComponentTag

Method onComponentTag(ComponentTag) is called to process a component tag, which can be freely manipulated through its argument of type org.apache.wicket.markup.ComponentTag. For example we can add/remove tag attributes with methods put(String key, String value) and remove(String key), or we can even decide to change the tag or rename it with method setName(String) (the following code is taken from project OnComponentTagExample):

Markup code:

  1. <head>
  2. <meta charset="utf-8" />
  3. <title></title>
  4. </head>
  5. <body>
  6. <h1 wicket:id="helloMessage"></h1>
  7. </body>

Java code:

  1. public class HomePage extends WebPage {
  2. public HomePage() {
  3. add(new Label("helloMessage", "Hello World"){
  4. @Override
  5. protected void onComponentTag(ComponentTag tag) {
  6. super.onComponentTag(tag);
  7. //Turn the h1 tag to a span
  8. tag.setName("span");
  9. //Add formatting style
  10. tag.put("style", "font-weight:bold");
  11. }
  12. });
  13. }
  14. }

Generated markup:

  1. <head>
  2. <meta charset="utf-8" />
  3. <title></title>
  4. </head>
  5. <body>
  6. <span wicket:id="helloMessage" style="font-weight:bold">Hello World</span>
  7. </body>

Just like we do with onInitialize, if we decide to override onComponentTag we must remember to call the same method of the super class because also this class may also customize the tag. Overriding onComponentTag is perfectly fine if we have to customize the tag of a specific component, but if we wanted to reuse the code across different components we should consider to use a behavior in place of this hook method.

We have already seen in chapter 6.2 how to use behavior AttributeModifier to manipulate the tag’s attribute. In chapter 19.1 we will see that base class Behavior offers also a callback method named onComponentTag(ComponentTag, Component) that can be used in place of the hook method onComponentTag(ComponentTag).

7.4.6. Methods onComponentTagBody

Method onComponentTagBody(MarkupStream, ComponentTag) is called to process the component tag’s body. Just like onComponentTag it takes as input a ComponentTag parameter representing the component tag. In addition, we also find a MarkupStream parameter which represents the page markup stream that will be sent back to the client as response.

onComponentTagBody can be used in combination with the Component‘s method replaceComponentTagBody to render a custom body under specific conditions. For example (taken from project OnComponentTagExample) we can display a brief description instead of the body if the label component is disabled:

  1. public class HomePage extends WebPage {
  2. public HomePage() {
  3. add(new Label("helloMessage", "Hello World"){
  4. @Override
  5. protected void onComponentTagBody(MarkupStream markupStream, ComponentTag tag) {
  6. if(!isEnabled())
  7. replaceComponentTagBody(markupStream, tag, "(the component is disabled)");
  8. else
  9. super.onComponentTagBody(markupStream, tag);
  10. }
  11. });
  12. }
  13. }

Note that the original version of onComponentTagBody is invoked only when we want to preserve the standard rendering mechanism for the tag’s body (in our example this happens when the component is enabled).

7.4.7. Methods onAfterRender

Called on each rendered component immediately after it has been rendered - onAfterRender() will even be called when rendering failed with an exception.

7.5. Removed stage

This stage is entered when a component is removed from its container hierarchy. The only hook method for this phase is onRemove(). If our component still holds some resources needed during rendering phase, we can override this method to release them.

Once a component has been removed we are free to add it again to the same container or to a different one. Starting from version 6.18.0 Wicket added a further hook method called onReAdd() which is triggered every time a previously removed component is re-added to a container. Please note that while onInitialize() is called only the very first time a component is added, onReAdd() is called every time it is re-added after having been removed.

7.6. Detached stage

When a request has finished, the page and all its contained components move a the detached stage:

The hook method onDetach() notifies each component that it should release all held resources no longer needed until the next request.

7.7. Summary

In this chapter we have seen which stages compose the lifecycle of Wicket components and which hook methods they provide. Overriding these methods we can dynamically modify the component hierarchy and we can enrich the behavior of our custom components.