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.
The following method is exposed by Control in order to handle Ajax requests:
isAjaxTarget(Context)
- Returns true if the control is the Ajax request target
,
false otherwise. The Ajax target control
is the Control
which onProcess
method will be invoked. Other
controls won't be processed. The most common way to target a specific
server side control is to give it an
HTML ID
attribute, which is then passed as an Ajax request parameter to the server.
More on this later.
The Behavior interface has been covered already so we'll look at AjaxBehavior next:
isAjaxTarget(Context)
- determines whether the AjaxBehavior is the request target or not. Click
will only invoke the AjaxBehavior onAction
method
if isAjaxTarget
returns true. This
allows for fine grained control over the exection of the onAction
method.
onAction(Control) - the AjaxBehavior action method for handling Ajax requests.
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:
setContent(String) - set the String content to render to the browser
setBytes(byte[]) - set the byte array to render to the browser
setTemplate(String) - set the name of the Velocity (or Freemarker) template to render to the browser
setModel(Map) - set the Velocity (or Freemarker) template model
setContentType(String)
- set the ActionResult content type, for example: text/html
,
text/xml
, application/json
etc.