ダウンロードする – リンク://wp-content/uploads/2010/07/Struts2-ModelDriven-Example.zip[Struts2-ModelDriven-Example.zip]
アクションが ”
ModelDriven
“インターフェースを実装する場合、フォームデータを自動的にオブジェクトに転送する
能力がさらに向上します
。
以下の完全な例を参照してください。
1.ドメインオブジェクト
セッターとゲッターメソッドを持つ顧客オブジェクト。
package com.mkyong.common; public class Customer{ String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2.アクション
Actionクラスは、
ModelDriven
インタフェースを実装し、
getModel()
メソッドを宣言して顧客のオブジェクトを返します。フォームデータがこのアクションに送信されると、自動的にフォームデータが顧客のプロパティに転送されます。
顧客オブジェクトは手動で初期化する必要があります。
-
CustomerAction.java **
package com.mkyong.common.action; import com.mkyong.common.Customer; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class CustomerAction extends ActionSupport implements ModelDriven{ //have to initialize it Customer customer = new Customer(); public String execute() throws Exception { return SUCCESS; } public Object getModel() { return customer; } }
3. JSPページ
-
ModelDriven ** デモンストレーションのJSPページ。
-
addCustomer.jsp **
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 ModelDriven example</h1> <h2>Add Customer</h2> <s:form action="customerAction" > <s:textfield name="name" label="Name"/> <s:textfield name="age" label="Age" value=""/> <s:submit/> </s:form> </body> </html>
-
success.jsp **
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 ModelDriven example</h1> <h2>Customer Details</h2> Name : <s:property value="name"/><br> Age : <s:property value="age"/><br> </body> </html>
4. struts.xml
すべてのリンク〜
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true"/> <package name="default" namespace="/" extends="struts-default"> <action name="addCustomerAction" class="com.mkyong.common.action.CustomerAction" > <result name="success">pages/addCustomer.jsp</result> </action> <action name="customerAction" class="com.mkyong.common.action.CustomerAction" > <result name="success">pages/success.jsp</result> </action> </package> </struts>
5.デモ
顧客フォームにアクセスし、フォーム(名前: “mkyong”、年齢 “123456”)
を入力し、送信ボタンを押すと、
フォームデータ(名前
リファレンス
ドキュメンテーション]