Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3
Warning
titleDojo plugin is deprecated

The Dojo plugin will be deprecated on Struts 2.1

Note
titleStruts 2.0 versus Struts 2.1 and the Dojo tags

The easiest way to get documentation for Struts 2.0 Dojo tag usage is to look at older Struts 2 documentation, like the Struts 2.0.11 Ajax tags wiki documentation.

Please check that documentation and the Dojo tag examples in the showcase app of the appropriate Struts 2 version before asking questions on the struts-user mailing list!


THE WIKI IS NOT VERSIONABLE (in a practical way).

The documentation here is for the most current Struts 2, not necessarily the most current release. We try to add version-specific documentation notes but have undoubtedly missed some locations.

Description

To use the AJAX tags from 2.1 on you must:

  • Include the Dojo Plugin distributed with Struts 2 in your /WEB-INF/lib folder.
  • Add <%@ taglib prefix="sx" uri="/struts-dojo-tags" %> to your page.
  • Include the head tag on the page, which can be configured for performance or debugging purposes.

Handling AJAX Responses

The following attributes affect the handling of all ajax responses.

Attribute

Default Value

Description

parseContent

true

When true, Dojo will parse the response into an XHTML Document Object and traverse the nodes searching for Dojo Widget markup. The parse and traversal is performed prior to inserting the nodes into the DOM. This attribute must be enabled to nest Dojo widgets (dojo tags) within responses. There's significant processing involved to create and parse the document so switch this feature off when not required. Note also that the response must be valid XHTML for cross-browser support and widgets must have unique IDs.

separateScripts

true

When true, Dojo will extract the <script> tags from the response, concatenate the extracted code into one block, create a new Function whose body is the extracted code and immediately invoke the function. The invocation is performed after the DOM has been updated with the XHTML. The function is executed within the scope of the widget (that is, the this variable points to the widget instance).
When false, Dojo will extract the <script> tags from the response, concatenate the extracted code into one block and:
*in IE: invoke window.execScript() on the code
*in other browsers: create a <script> node containing the code and insert that node into the DOM
This invocation occurs after the DOM has been updated with the XHTML. Note that scripts may not be executed if it is not valid to create a <script> node in the DOM at the destination.

executeScripts

false

When true, Dojo will extract code from the <script> tags from the response and execute it based on the separateScripts value.
When false, the XHTML response is inserted into the DOM and <script> nodes are ignored.

Note

It's possible that the updated DOM will not include <script> nodes even though the inline code has been executed.

Tip

Ensure the response is XHTML-compliant (including, for example, thead and tbody tags in tables).
If you intend to run inline javascript:
*Ensure the javascript can be concatenated and executed in one block,
*set executeScripts=true,
*set separateScripts=true (the reliable option)

Topics

Most of the AJAX tags use Dojo topics for event notification and communication between them, to learn about topics visit Dojo's documentation

Examples

Examples can be found on the documentation for each tag in the UI Tag Reference page, for additional examples see Ajax and JavaScript Recipes and the Showcase application distributed with Struts 2.

Tags

Note

The Ajax Theme and Ajax Tags are experimental. Feedback is appreciated!

The framework provides a set of tags to help you ajaxify your applications, on Dojo. Dojo 0.4 is bundled with the distribution.

Tip

To use the Ajax tags you need to set the "theme" attribute to "ajax". Use the head tag to configure the page for the ajax theme. Set the "debug" attribute of the head tag to "true" to display debug information on the bottom of the page.

General Information

 

Common AJAX Tag Attributes

The Ajax tags share a set of common attributes.

Preventing/Canceling a Request

How to prevent or cancel a request.

Request Indicators

How to indicate an Ajax request is processing.

DOJO Topics

Use JavaScript to publish or listen to Dojo topics (events).

AJAX Urls

The URLs of Ajax tags ("href" attribute) must be built with the <s:url.../> tag!

Basic Ajax Tags

 

<s:div>

Creates a content area that can load its content via Ajax, optionally refreshing.

<s:submit>

Updates element(s) or submits a form via Ajax.

<s:a> (Anchor)

Updates element(s) via Ajax.

<s:tabbedPanel>

Creates a tabbed panel containing static or dynamic <s:div.../> tab contents.

<s:autocompleter>

Autocompleter tag providing suggestions or updating elements based on current value.

...

Common Attributes

These attributes are common to all the ajax tags:

Attribute

Description

Type

href

url used to make the request

String

listenTopics

A comma separated list of topics names, which will cause the tag to reload its content (Div, Autocompleter), or perform an action (Anchor, Submit)

String

notifyTopics

A comma separated list of topics names, published by the tag, parameters "data", "type" and "request" will be passed. See each tag for details.

String

showErrorTransportText

Sets whether or not error messages should be displayed ("true" by default)

Boolean

indicator

The id of an element that will be displayed while a request is in progress

String

...

Preventing a request

The third parameter of "notifyTopics", request, has a "cancel" property that can be used to prevent a request.

Example:

...


<script type="text/javascript" language="javascript">
dojo.event.topic.subscribe("/request", function(data, type, request) {
  //cancel request
  request.cancel= true;
});
</script>

<s:url 
  id="ajaxTest" 
  value="/AjaxTest.action" />
 
<s:submit 
  type="submit" 
  theme="ajax" 
  value="submit" 
  notifyTopics="/request" 
  href="%{ajaxTest}"/>

...

Indicators

Use indicators to notify the user that a request is in progress. The indicator should be hidden when the page is loaded.

This indicator is an image:

...


<img style="display:none" src="${pageContext.request.contextPath}/images/indicator.gif" alt="Loading..."/>

...

Topics

Topics provide an easy way to listen to and publish events.

To listen to a topic:

...


dojo.event.topic.subscribe("/refresh", function(param1, param2) {
  //this function will be called everytime "/refresh" is published
});

To publish a topic:

...


dojo.event.topic.publish("/refresh", "foo", "bar"); 

...

URL

The "href" attribute must contain a url built with the url tag.

Example:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />
<s:div theme="ajax" href="%{ajaxTest}">
  Initial Content
</s:div>

...

None of the ajax tags will work if their url (in the "href" attribute) is not built with the url tag.

...

Returning pages with AJAX Tags

Ajax tags can be used inside content returned from an asynchronous request, just like in regular pages.

...

Div

The div tag is a content area that can load its content asynchronously. The div tag can be forced to reload its content using topics. To define the topics that will trigger the refresh of the panel, use the "listenTopics" attribute. This tag will load its content when the page is loaded, unless "autoStart" is set to "false".

Note

While Dojo supports crossdomain XHR using IFrames, the S2 Ajax tags do not (yet).

Examples

This div will refresh every time the topics "/refresh0" or "/refresh1" are published:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div theme="ajax" href="%{ajaxTest}" listenTopics="/refresh0,/refresh1"/>

The div tag can be configured to update its content periodically, using a timer. Use the "updateFreq" attribute to set the interval for the timer; this value is expressed in milliseconds. If "autoStart" is set to true, "delay" can be used to cause the timer to wait for the delay period (in milliseconds also) before starting.

This div will refresh periodically, every 2 seconds, starting 3 seconds after the page is loaded:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div theme="ajax" href="%{ajaxTest}" updateFreq="2000" delay="3000"/>

The "autoStart" attribute controls whether the timer will be started when the page is loaded; its value is "true" by default. The timer can be started and stopped using the topics "startTimerListenTopics" and "stopTimerListenTopics".

This div will not start the timer by default and will listen to the start/stop topics to control the timer:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div 
  theme="ajax" 
  href="%{ajaxTest}" 
  startTimerListenTopics="/startTimer" 
  stopTimerListenTopics="/stopTimer" 
  updateFreq="3000" 
  autoStart="false"/>

The div panel shows "Loading..." by default when the request is in process. To customize this text, use the "loadingText" attribute. If an error of any sort occurs, the error will be shown in the div area; to customize the error message, use the "errorText" attribute. If you don't want to display the erro, set "showErrorTransportText" to "false".

This div uses custom error/loading messages:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div 
  href="%{ajaxTest}" 
  theme="ajax" 
  errorText="There was an error" 
  loadingText="reloading" 
  updateFreq="5000"/>

If the loaded content contains Javascript code sections, these sections will be executed if the "executeScripts" attribute is set to true.

If parameters need to be passed to the url, the "formId" attribute can be used to specify a form whose fields will be serialized and passed in the request as parameters. The attribute "formFilter" can bet set to the name of a Javascript function that will be used to filter the fields of "formId". The "formFilter" function will be called for each field, passing the field's DOM node as a parameter, and must return true if the field is to be included, or false otherwise.

This div will submit the field "firstName" of the form "userData" and ignore other fields:

...


<script type="text/javascript">
  function filter(field) {
    return field.name == "firstName";
  }
</script>

<form id="userData">
  <label for="firstName">First Name</label>
  <input type="textbox" id="firstName" name="firstName">
  <label for="lastName">Last Name</label>
  <input type="textbox" id="lastName" name="lastName">
</form>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div href="%{ajaxTest}" theme="ajax" formId="userData" formFilter="filter"/>

If the attribute "handler" is set, the Javascript function specified by its value will be called, instead of making the request. Use the "handler" function when you want to handle the request yourself.

This div will not make any request, and will just call the function "handler". The first parameter of the function is the Dojo widget for the div, and the second the DOM node for the div.

...


<script type="text/javascript">
   function handler(widget, node) {
     alert('I will handle this myself!');
     node.innerHTML = "Done";
   }
</script>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:div theme="ajax" href="%{ajaxTest}" handler="handler"/>

"notifyTopics" scenarios:

When

data

type

request

Before request

div's id, or Dojo widget id for this element if the div's id was not provided

"before"

empty javascript object

After successful request

html string

"load"

request javascript object

After unsuccessful request

html string

"error"

request javascript object

Attribute

Description

Type

handler

Javascript function name that will make the request

String

formId

Form id whose fields will be serialized and passed as parameters

String

formFilter

Function name used to filter the fields of the form

String

loadingText

The text to display in the div while content is loaded

String

errorText

The text to display in the div when there is an error

String

refreshListenTopic

Topic name that will cause the div content to be reloaded

String

startTimerListenTopics

Topic names that will start the timer (comma separated)

String

stopTimerListenTopics

Topic names that will stop the timer

String (comma separated)

executeScripts

Any Javascript code in the loaded content will be executed

Boolean

updateFreq

Time between requests (in milliseconds)

Integer

delay

Time to wait before making the first request (in milliseconds)

Integer

autoStart

Start timer automatically when page loads

Boolean

afterLoading

Deprecated. Use "notifyTopics" instead

String

...

Submit

The submit tag can be used to update the content of its "targets" attribute with text returned from the asynchronous request. "targets" is a comma-delimited list of element ids. The "targets" attribute is optional.

Regular submit button that will update the content of div1:

...


<div id="div1">Div 1</div>

<s:url id="ajaxTest" value="/AjaxTest.action" />
 
<s:submit 
  type="submit" 
  theme="ajax" 
  value="submit" 
  targets="div1" 
  href="%{ajaxTest}"/>

Submit button using an image:

...


<div id="div1">Div 1</div>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:submit 
  type="image" 
  theme="ajax" 
  label="Alt Text" 
  targets="div1" 
  src="${pageContext.request.contextPath}/images/struts-rocks.gif" 
  href="%{ajaxTest}"/>

If the submit button is used inside a form (href is not required on this case), the form will be submitted asynchronously:

...


<s:form id="form" action="AjaxTest">
  <input type="textbox" name="data">
  <s:submit type="button" theme="ajax" label="Update Content"/>		
</s:form>

A submit button can be used to submit a form, even if it is outside the form, using "formId", "formFilter" and "href". Note that in this case "href" is required.

...


<s:form id="form1">
  <input type="textbox" name="data">	
</s:form>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:submit type="submit" theme="ajax" href="%{ajaxTest}" formId="form1"/>	

See the Div tag for examples on how to use "handler", "loadingText" and "errorText".

"notifyTopics" scenarios:

When

data

type

request

Before request

submit's id, or Dojo widget id for this element if the submit's id was not provided

"before"

empty javascript object

After successful request

html string

"load"

request javascript object

After unsuccessful request

html string

"error"

request javascript object

Attribute

Description

Type

targets

Comma delimited list of ids of the elements whose content will be updated

String

handler

Javascript function name that will make the request

String

formId

Form id whose fields will be serialized and passed as parameters

String

formFilter

Function name used to filter the fields of the form

String

loadingText

The text to display in the "targets" while content is loaded

String

errorText

The text to display in the "targets" when there is an error

String

refreshListenTopic

Topic name that will cause the "targets" content to be reloaded

String

executeScripts

Any Javascript code in the loaded content will be executed

Boolean

src

Supply an image src for "image" type submit button. Will have no effect for types "input" and "button"

String

resultDivId

Deprecated. Use "targets" instead

String

preInvokeJS

Deprecated. Use "notifyTopics" instead

String

onLoadJS

Deprecated. Use "notifyTopics" instead

String

...

Anchor

The anchor tag, like the submit tag, can be used to update the content of its "targets" attribute with text returned from the asynchronous request. "targets" is a comma-delimited list of element ids. The "targets" attribute is optional.

This anchor will update the content of div1 and div2 with text returned form "/AjaxTest.action"

...


<div id="div1">Div 1</div>
<div id="div2">Div 2</div>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:a theme="ajax" href="%{ajaxTest}" targets="dev1,dev2">Update divs</s:a>

If the anchor tag is used inside a form (href is not required on this case), the form will be submitted asynchronously:

...


<s:form id="form" action="AjaxTest">
  <input type="textbox" name="data">
  <s:a theme="ajax">Submit form</s:a>		
</s:form>

Using the anchor tag to submit a form:

...


<s:form id="form1">
  <input type="textbox" name="data">	
</s:form>

<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:a theme="ajax" href="%{ajaxTest}" formId="form1">Submit form</s:a>

See the Div tag for examples on how to use "handler", "loadingText" and "errorText"

"notifyTopics" scenarios:

When

data

type

request

Before request

anchor's id, or Dojo widget id for this element if the anchor's id was not provided

"before"

empty javascript object

After successful request

html string

"load"

request javascript object

After unsuccessful request

html string

"error"

request javascript object

Attribute

Description

Type

targets

Comma delimited list of ids of the elements whose content will be updated

String

handler

Javascript function name that will make the request

String

formId

Form id whose fields will be serialized and passed as parameters

String

formFilter

Function name used to filter the fields of the form

String

loadingText

The text to display in the "targets" while content is loaded

String

errorText

The text to display in the "targets" when there is an error

String

refreshListenTopic

Topic name that will cause the "targets" content to be reloaded

String

executeScripts

Any Javascript code in the loaded content will be executed

Boolean

preInvokeJS

Deprecated. Use "notifyTopics" instead

String

afterLoading

Deprecated. Use "notifyTopics" instead

String

...

Tabbed Panel

The tabbedPanel tag can host static and dynamic (asynchronously loaded) tabs. Every div tag inside the tabbedPanel will be rendered as a tab. The "label" attribute is required for each tab, and will be used as its caption. For more details on the dynamic tabs, see the "div" tag section. The tabbedPanel tag is in the "simple" theme bacause it does not contains any ajax functionality itself.

Note
titleThemes

Do not set the "theme" attribute to "ajax" for the tabbedPanel tag itself.

Do, however, set the "theme" attribute to "ajax" for each tab, and provide a valid "href" attribute for each dynamic tab (div).

This tabbedPanel has one static, and one dynamic tab:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:tabbedPanel>
    <s:div label="static">
        This is an static content tab.
    </s:div>
    <s:div href="%{ajaxTest}" theme="ajax" label="dynamic">
        This is a dynamic content tab. 
        The content of this div will be replaced with the text returned from "/AjaxTest.action"
    </s:div>
</s:tabbedPanel>  

Use the "labelposition" attribute to specify the side where the tab labels must be placed, possible values are "top" (default), "right", "bottom" and "left". Tabs can have a "close button" which will remove the tab from its tabbedPanel parent. The "close button" is hidden by default, to make it visible set the "closeButton" attribute to either "panel" (it will be placed on the tabbedPanel), or "tab" (it will be placed on each tab). By default the first tab will be selected, using the "selectedTab" attribute, you can specify the id of the tab to be selected when the page loads.

This tabbedPanel will place the tab labels on the left, with a "close" button on each tab, and will select the "dynamic" tab by default:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:tabbedPanel labelposition="left" closeButton="tab" selectedTab="dynamic">
    <s:div label="static" id="static">
        This is an static content tab.
    </s:div>
    <s:div href="%{ajaxTest}" theme="ajax" label="dynamic" id="dynamic">
        This is a dynamic content tab. 
        The content of this div will be replaced with the text returned from "/AjaxTest.action"
    </s:div>
</s:tabbedPanel>  

TabbedPanel's height will be by default the same as the currently selected tab, use the "doLayout" attribute to force a fixed height.

This tabbedPanel's height is 300 px:

...


<s:url id="ajaxTest" value="/AjaxTest.action" />

<s:tabbedPanel id="test2" theme="simple" cssStyle="height: 300px;" doLayout="true">
  <s:div id="left" label="left">
      This is the left pane<br/>
      <s:form >
          <s:textfield name="tt" label="Test Text" /> 
          <br/>
          <s:textfield name="tt2" label="Test Text2" />
      </s:form>
  </s:div>
  <s:div theme="ajax"  href="%{ajaxTest}" id="ryh1" label="remote one" />
</s:tabbedPanel>

Attribute

Description

Type

closeButton

Where the close button will be placed, possible values are "tab" and "pane"

String

selectedTab

The id of the tab that will be selected by default

String

doLayout

If doLayout is false (default), the tabbedPanel's height is the height of the currently selected tab

Boolean

labelposition

Where to place the tabs, possible vales are "top" (default), "right", "bottom" and "left"

String

...

Autocompleter

The autocompleter tag loads its options asynchronously when the page loads, and suggests options based on the text entered in the textbox. If the attribute "autoComplete" is set to "true" (defaults to false), the autocompleter will make suggestions in the textbox, as the user types. The autocompleter will always display a dropdown with the options that have at least a partial match with the text entered in the textbox. If the user clicks on the dropdown button, all the options will be shown in the dropdown. To force the value to be a valid option set the attribute "forceValidOption" to "true" ("false" by default).

Every autocompleter tag will generate two input fields, one of type "text", whose name is specified with the "name" attribute, and one of type "hidden" whose name is "${name}Key", where ${name} is the value in the "name" attribute. Given the following form:

...


<s:url id="json" value="/JSONList.action" />

<form action="/someurl">
  <s:autocompleter theme="ajax" href="%{json}" name="state"/>
  <input type="submit">
</form>

When the form is submitted, the request will be something like: /someurl?state=Florida&stateKey=FL. "state" and "stateKey" must be defined as properties of the target action for the url.

Warning
titleRequired properties

Two properties must be defined on the target action for each autocompleter, one for the displayed text (its name is the value of the "name" attribute), and one for the key or value (its name is the value of the "name" attribute plus "Key").

Note
titleAutocompleter input format

Wiki Markup
    The text to be returned from your action must be a list in [JSON|http://json.org/] (Javascript Object Notation).
    Make sure your action returning the JSON list is not decorated adding any extra content.
    Like:
    [
        \["Display Text1", "Value1"\],
        \["Display Text2", "Value2"\]
    ]

Warning
titleEscape character on returned text

Remember to escape characters like \ and ' on the text returned from the action used with the autocompleter tag. See JSON documentation for more details.

This is a simple autocompleter without textbox autocomplete:

...


<s:url id="json" value="/JSONList.action" />

<s:autocompleter theme="ajax" href="%{json}" autoComplete="false"/>

This tag can be used in the "simple" theme, without ajax functionality. When using this tag in the "simple" theme, the option to be selected by default can be specified using the "value" attribute. Use the "list" attribute to specify the available options:

...


<s:autocompleter theme="simple" list="{'apple','banana','grape','pear'}" value="grape"/>

By default the dropdown's height is 120 px, if the list contains just a few items and is smaller than 120 px, the dropdown's height will be adjusted to the size of the list. To change the default value for the dropdown's height use the "dropdownHeight" attribute.

This autocompleter dropdown's height is 180 px:

...


<s:url id="json" value="/JSONList.action" />

<s:autocompleter theme="ajax" href="%{json}" dropdownHeight="180"/>

When the topic specified in the "refreshListenTopic" attribute is published, the options in the autocompleter will be reloaded. If the "onValueChangedPublishTopic" attribute is given a value, every time the selected value changes, a topic with that name will be published. This two attributes can be use to link two autocompleters. The "formId" and "formFilter" attributes (see Div tag for examples) can be used to submit a form, when the request is made.

When the selected value in "Autocompleter 1" changes, the "/Refresh" is published, forcing "Autocompleter 2", to reloads its options, submitting the form "selectForm":

...


<s:url id="json" value="/JSONList.action" />

<form id="selectForm">
  Autocompleter 1 <s:autocompleter theme="simple" name="select" list="{'fruits','colors'}"  notifyTopics="/Refresh" />
</form>
  Autocompleter 2 <s:autocompleter theme="ajax" href="%{json}" formId="selectForm" listenTopics="/Refresh"/>

By default the autocompleter tag loads its options once, and makes suggestions based on those options. This is not the best approach if the action returns many options. The autocompleter tag can reload its options every time the user types in the textbox, setting "loadOnTextChange" to "true" ("false" by default). If "loadOnTextChange" is set to "true" the available options will be reloaded after the user types 3 characters (default), to specify the minimum number of characters, use "loadMinimumCount". On this case, it is probably desired to hide the dropdown arrow, setting "showDownArrow" to "false".

This autocompleter reloads its content everytime the user types into the textbox, and the text length is greater than or equal to 4:

...


<s:url id="json" value="/JSONList.action" />

<s:autocompleter theme="ajax" href="%{jsonList}" loadOnTextChange="true" loadMinimumCount="4" showDownArrow="false"/>

"notifyTopics" scenarios:

When

data

type

request

Before request

autocompleter's id, or Dojo widget id for this element if the autocompleter's id was not provided

"before"

empty javascript object

After successful request

html string

"load"

request javascript object

After unsuccessful request

html string

"error"

request javascript object

Value changed

new value

"valuechanged"

empty javascript object

Attribute

Description

Type

autoComplete

Whether to make suggestions on the textbox (suggestions in the dropdown will still be made, disregarding the value of this property)

Boolean

forceValidOption

The text entered has to match an option, otherwise the value will be cleared when autocompleter loses focus

Boolean

delay

Time to wait before making the search (in milliseconds)

Integer

searchType

How to match entered text agains the available options, "startstring" (default), "startword" and "substring"

String

dropdownHeight

The height of the dropdown (in pixels), by default 120

Integer

dropdownWidth

The width of the dropdown (in pixels), by default same as autocompleter's width

Integer

formId

Form id whose fields will be serialized and passed as parameters

String

formFilter

Function name used to filter the fields of the form

String

value

Default value when "theme" is "simple"

String

list

Iteratable source to populate options

String

loadOnTextChange

Reload options as user types

Boolean

loadMinimumCount

Text lenght that will trigger a reload of the options if "loadOnTextChange" is set to "true", 3 by default

Integer

showDownArrow

Show or hide the dropdown arrow, "true" by default

Boolean

...