AjaxTags 專案的做法,是在既有的 Struts HTML 標記庫之上補上 Ajax 支援。它改寫了 Struts 的 org.apache.struts.taglib.html.FormTag 與 BaseHandlerTag 這兩個標籤類,並借助 Struts 的 plugin 機制,讓原本不支援 Ajax 的 Struts 具備了非同步更新的能力。
使用起來幾乎跟原本的 Struts 標籤沒兩樣,只是多了幾個 Ajax 相關屬性:
<html:form action="example1" ajaxRef="example1">
First Name: <html:text property="firstName" size="25" value="Frank" />
<br>
Last Name: <html:text property="lastName" size="25" value="Zammetti" />
<br>
<html:button property="button" value="Click to do Ajax!" ajaxRef="button" />
</html:form>
Result:<br>
<span id="example1_resultLayer"></span>
關鍵在 ajaxRef 屬性。它的值對應到 ajax-config.xml 中的定義,本範例的設定如下:
<!DOCTYPE ajaxConfig PUBLIC "ajaxConfig" "ajaxConfig">
<ajaxConfig>
<!-- 自訂的請求處理器,用來產生 XML -->
<handler name="CustomXMLGenerator" type="request">
<function>customGenerateXML</function>
<location>customXMLGenerator.js</location>
</handler>
<!-- example 1 的設定 -->
<form ajaxRef="example1">
<element ajaxRef="button">
<event type="onclick">
<requestHandler type="std:QueryString">
<target>example1.do</target>
<parameter>firstName=firstName,lastName=lastName</parameter>
</requestHandler>
<responseHandler type="std:InnerHTML">
<parameter>example1_resultLayer</parameter>
</responseHandler>
</event>
</element>
</form>
</ajaxConfig>
從這份設定檔可以看出它的分工:表單有哪些欄位、哪個按鈕觸發什麼事件、請求要送到哪裡、回應又要寫回哪個區塊,全部以宣告式的方式描述,完全不必手写 XMLHttpRequest 的細節。這是一種相當巧妙的封裝。
當然,AjaxTags 距離真正實用還有段路要走,但它示範了一個有價值的思路:如何在既有框架之上,用最小的侵入成本替老系統補上 Ajax 能力。