这里我们创建一个web工程为:struts2-modeldrive ,用于讲解演示Struts2模型驱动这一章内容的学习。
如果一个动作实现了“模型驱动”- ModelDriven 接口,它就获得了表单数据自动传输到对象的额外能力。请参见下面的完整的例子:
1. 域对象
一个顾客(customer)对象,有 setter 和 getter 方法。
Customer.java
package com.yiibai.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
Action类,实现了模型驱动ModelDriven 接口,声明getModel()方法返回客户的对象。当表单数据提交到这个动作,它会自动将表单数据传输到客户的属性。
客户对象必须手动初始化。
CustomerAction.java
package com.yiibai.common.action;
import com.yiibai.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页面
JSP页面的模型驱动(ModelDriven)的示范。
addCustomer.jsp
Struts 2 ModelDriven example
Add Customer
success.jsp
Struts 2 ModelDriven example
Customer Details
Name :
Age :
4. struts.xml
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
class="com.yiibai.common.action.CustomerAction" >
pages/addCustomer.jsp
class="com.yiibai.common.action.CustomerAction" >
pages/success.jsp
5. 示例
访问客户表,填写表格 (name : “yiibai.com”, age ” “26”) 并点击提交按钮,表单数据(name & age) 将自动转移到客户的属性(name & age) (按属性名称匹配)。
http://localhost:8080/struts2-modeldrive/addCustomerAction.action
http://localhost:8080/struts2-modeldrive/customerAction.action
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。