4.2. AjaxBehavior

AjaxBehavior is an interface that extends Behavior (covered earlier) and adds the ability to handle and process incoming Ajax requests.

Click also provides a default AjaxBehavior implementation, DefaultAjaxBehavior. Using this class you only need to implement the methods you are interested in.

AjaxBehaviors, like Behaviors, are added to controls through the AbstractControl.addBehavior() method.

AjaxBehaviors provides an onAction method (similar to ActionListener) that is invoked to handle Ajax requests. The onAction method returns an ActionResult containing the data to be rendered to the browser.

The Control, Behavior, AjaxBehavior and ActionResult classes are depicted in the figure below.

Ajax Behavior Class Diagram

Figure 4.1. Ajax Behavior Class Diagram


The following method is exposed by Control in order to handle Ajax requests:

The Behavior interface has been covered already so we'll look at AjaxBehavior next:

The onAction method returns an ActionResult instance, containing the data to be rendered to the browser. ActionResult can return any type of response: String, byte array or a Velocity (Freemarker) template.

The isAjaxTarget method controls whether or not the onAction method should be invoked. isAjaxTarget() is typically used to target the AjaxBehavior for specific JavaScript events. For example an AjaxBehavior might only handle click or blur JavaScript events. Of course the client-side code initiating the Ajax request should pass the JavaScript event to the server.

Lastly the ActionResult methods are shown below: