WebWork2では基本的にActionのフィールドに入力パラメータを保持します。
しかし、StrutsのActionFormのように入力パラメータを受け取るクラスを作ることも出来ます。
WebWork2ではその仕組みをModelDrivenと呼んでいます。
入力値を格納するクラスを作成
public class MultiInputField { private List value = new XWorkList(MultiInputFieldValue.class); public List getValue() { return value; } public void setValue(List value) { this.value = value; } }
ActionクラスでModelDrivenインターフェースを実装
getModel()メソッドで入力値格納用クラスのインスタンスを返します。
public class ModelDrivenAction extends ActionSupport implements ModelDriven { private MultiInputField input = new MultiInputField(); public Object getModel() { return input; } public String execute() throws Exception { System.out.println(input.getValue()); return SUCCESS; } public Object getValue(int i) { return input.getValue().get(i); } }
xwork.xmlの設定
intercepterにmodelDrivenStackを設定します。
<action name="modeldriven" class="ww2.examples.event.ModelDrivenAction"> <interceptor-ref name="modelDrivenStack"/> <result name="success" type="dispatcher"> <param name="location">/WEB-INF/vm/modeldriven.vm</param> </result> </action>
modeldriven.vm
formのaction以外はmultiinputfield.vmと同じです。
<form action="modeldriven.action" method="POST"> <table> <tr><th>checkbox</th><th>text</th><th>select</th></tr> #foreach ( $item in [1..3] ) #set($num = $item - 1) <tr> <td><input type="checkbox" name="value[$num].check" value="true" ) #if($action.getValue($num).check) checked #end/></td> <td> <input type="text" name="value[$num].text" value="$!action.getValue($num).text"/> </td> <td> <select name="model.value[$num].select"> <option #if($action.getValue($num).select == "A") selected #end>A</option> <option #if($action.getValue($num).select == "B") selected #end>B</option> <option #if($action.getValue($num).select == "C") selected #end>C</option> </select> </td> </tr> #end </table> <input name="aaa"> <input type="submit" value="実行" /> </form>
結果
「7.Velocityでのリクエストパラメータの再表示」の「可変リクエストパラメータ」の場合の時と同じです。