Struts 2 ModelDrivenの例

Struts 2 ModelDrivenの例

ダウンロード–Struts2-ModelDriven-Example.zip

アクションが「ModelDriven」インターフェースを実装している場合、アクションはtransfer the form data into the object automaticallyに追加の機能を取得します。 以下の完全な例を参照してください。

1. ドメインオブジェクト

setterおよびgetterメソッドを備えた顧客オブジェクト。

Customer.java

package com.example.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. アクション

アクションクラスは、ModelDrivenインターフェイスを実装し、getModel()メソッドを宣言して顧客のオブジェクトを返します。 フォームデータがこのアクションに送信されると、フォームデータが顧客のプロパティに自動的に転送されます。

顧客オブジェクトは手動で初期化する必要があります。

CustomerAction.java

package com.example.common.action;

import com.example.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" %>





Struts 2 ModelDriven example

Add Customer

success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>





Struts 2 ModelDriven example

Customer Details

Name :
Age :

4. struts.xml

それをすべてリンクしてください〜




    

    

        
            pages/addCustomer.jsp
        

        
            pages/success.jsp
        

    

5. Demo

顧客フォームfill in the form (name : “example”, age ” “123456”)にアクセスし、送信ボタンform data (name & age) will be transferred into the customer’s properties (name & age)(プロパティ名で一致)を自動的に押します。

Struts2 model driven example

Struts 2 model driven example